我正在通过SSH (Putty)在Linux机器上工作。我需要让一个进程在夜间运行,因此我认为可以通过在后台启动该进程(在命令末尾使用&号)并将stdout重定向到一个文件来实现这一点。

令我惊讶的是,这行不通。只要我关闭Putty窗口,进程就会停止。

我怎样才能防止这种情况发生?


当前回答

使用屏幕。它使用起来非常简单,就像终端的vnc一样。 http://www.bangmoney.org/presentations/screen.html

其他回答

当会话关闭时,进程接收到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.

如果使用screen作为根用户运行进程,请注意特权提升攻击的可能性。如果你自己的帐户以某种方式被泄露,将有一种直接的方式接管整个服务器。

如果需要定期运行此进程,并且您对服务器有足够的访问权限,那么更好的选择是使用cron来运行该作业。你也可以使用init。D(超级守护进程)在后台启动您的进程,并且它可以在完成后立即终止。

我也会去屏幕程序(我知道some1其他答案是屏幕,但这是一个完成)

事实不仅是&,ctrl+z bg disown, nohup等可能会给你一个讨厌的惊喜,当你退出工作仍然会被杀死(我不知道为什么,但它确实发生在我身上,它没有打扰它,因为我切换到使用屏幕,但我猜anthonyrisinger解决方案作为双分叉将解决这个问题),屏幕也有一个主要的优势,只是背景:

screen will background your process without losing interactive control to it

顺便说一句,这是一个我一开始就不会问的问题:)…我从一开始在Unix上做任何事情就使用screen…我(几乎)从未在unix/linux shell中工作而不首先开始屏幕…我现在应该停止了,否则我将开始无休止的演示什么是好屏幕以及可以为你们做什么……自己去查吧,很值得的;)

如果你想同时运行X个应用程序,可以使用xpra和“screen”。

使用屏幕。它使用起来非常简单,就像终端的vnc一样。 http://www.bangmoney.org/presentations/screen.html