我正在通过SSH (Putty)在Linux机器上工作。我需要让一个进程在夜间运行,因此我认为可以通过在后台启动该进程(在命令末尾使用&号)并将stdout重定向到一个文件来实现这一点。
令我惊讶的是,这行不通。只要我关闭Putty窗口,进程就会停止。
我怎样才能防止这种情况发生?
我正在通过SSH (Putty)在Linux机器上工作。我需要让一个进程在夜间运行,因此我认为可以通过在后台启动该进程(在命令末尾使用&号)并将stdout重定向到一个文件来实现这一点。
令我惊讶的是,这行不通。只要我关闭Putty窗口,进程就会停止。
我怎样才能防止这种情况发生?
当前回答
nohup blah &
用您的进程名替换blah!
其他回答
nohup blah &
用您的进程名替换blah!
将此字符串附加到您的命令:>&- 2>&- <&- &。>&-表示关闭标准输出。2>&-表示关闭stderr。<&-表示关闭stdin。&意味着在后台运行。这也可以通过ssh以编程方式启动作业:
$ ssh myhost 'sleep 30 >&- 2>&- <&- &'
# ssh returns right away, and your sleep job is running remotely
$
对于大多数进程,您可以使用这个旧的Linux命令行技巧进行伪守护:
# ((mycommand &)&)
例如:
# ((sleep 30 &)&)
# exit
然后启动一个新的终端窗口,然后:
# ps aux | grep sleep
将显示睡眠30仍在运行。
您所做的是将该进程作为子进程的子进程启动,当您退出时,通常会触发该进程退出的nohup命令不会级联到子进程,使其成为一个孤儿进程,仍在运行。
我更喜欢这种“设置好就忘记”的方法,不需要处理nohup、screen、tmux、I/o重定向或任何类似的东西。
当会话关闭时,进程接收到SIGHUP信号,但它显然没有捕捉到这个信号。您可以在启动进程时使用nohup命令,或者在启动进程后使用bash内置命令disown -h来防止这种情况发生:
> help disown
disown: disown [-h] [-ar] [jobspec ...]
By default, removes each JOBSPEC argument from the table of active jobs.
If the -h option is given, the job is not removed from the table, but is
marked so that SIGHUP is not sent to the job if the shell receives a
SIGHUP. The -a option, when JOBSPEC is not supplied, means to remove all
jobs from the job table; the -r option means to remove only running jobs.
看看“nohup”程序。