是否可以检测用户输入命令多长时间
Is it possible to detect how long hasn't user type command
我正在研究 Linux shell 我正在尝试编写一个脚本,它就像下面的触发器:
if user hasn't typed any command for 2 min
execute some executable file
fi
如果我有这样的脚本,我可以把它做成守护进程。例如,我可以让我的系统这样做:
if user stops typing command for 2 min
shutdown -h now
fi
您需要小心...例如,如果命令本身的执行时间超过 2 分钟怎么办?在这种情况下可能不需要关闭系统。
获得此行为的唯一方法是从 shell 应用程序(而不是作为单独的实体/守护程序)内部,您可以在其中了解状态 -
例如:GETTING_COMMAND
,或 EXECUTING_COMMAND
...
在 bash
中您可以使用 TMOUT
variable:
TMOUT
If set to a value greater than zero, TMOUT is treated as the default timeout for the read builtin (see Bash Builtins). The select command (see Conditional Constructs) terminates if input does not arrive after TMOUT seconds when input is coming from a terminal.
In an interactive shell, the value is interpreted as the number of seconds to wait for a line of input after issuing the primary prompt. Bash terminates after waiting for that number of seconds if a complete line of input does not arrive.
请注意,这也会影响脚本对 read
或 select
的任何调用。
像这样的东西可以满足您的需求:
export TMOUT=120
bash
shutdown -h now
如果您正在开发自己的 shell,那么您当然可以在获取用户输入的同时使用 select(2)
之类的东西。
我正在研究 Linux shell 我正在尝试编写一个脚本,它就像下面的触发器:
if user hasn't typed any command for 2 min
execute some executable file
fi
如果我有这样的脚本,我可以把它做成守护进程。例如,我可以让我的系统这样做:
if user stops typing command for 2 min
shutdown -h now
fi
您需要小心...例如,如果命令本身的执行时间超过 2 分钟怎么办?在这种情况下可能不需要关闭系统。
获得此行为的唯一方法是从 shell 应用程序(而不是作为单独的实体/守护程序)内部,您可以在其中了解状态 -
例如:GETTING_COMMAND
,或 EXECUTING_COMMAND
...
在 bash
中您可以使用 TMOUT
variable:
TMOUT
If set to a value greater than zero, TMOUT is treated as the default timeout for the read builtin (see Bash Builtins). The select command (see Conditional Constructs) terminates if input does not arrive after TMOUT seconds when input is coming from a terminal. In an interactive shell, the value is interpreted as the number of seconds to wait for a line of input after issuing the primary prompt. Bash terminates after waiting for that number of seconds if a complete line of input does not arrive.
请注意,这也会影响脚本对 read
或 select
的任何调用。
像这样的东西可以满足您的需求:
export TMOUT=120
bash
shutdown -h now
如果您正在开发自己的 shell,那么您当然可以在获取用户输入的同时使用 select(2)
之类的东西。