我正在通过SSH (Putty)在Linux机器上工作。我需要让一个进程在夜间运行,因此我认为可以通过在后台启动该进程(在命令末尾使用&号)并将stdout重定向到一个文件来实现这一点。
令我惊讶的是,这行不通。只要我关闭Putty窗口,进程就会停止。
我怎样才能防止这种情况发生?
我正在通过SSH (Putty)在Linux机器上工作。我需要让一个进程在夜间运行,因此我认为可以通过在后台启动该进程(在命令末尾使用&号)并将stdout重定向到一个文件来实现这一点。
令我惊讶的是,这行不通。只要我关闭Putty窗口,进程就会停止。
我怎样才能防止这种情况发生?
当前回答
如果您想将详细信息记录到一个文件中,Nohup非常有用。但当它进入后台时,如果你的脚本要求,你无法给它一个密码。我想你一定要试一下屏幕。它是一个实用工具,你可以使用yum安装在你的linux发行版上,例如在CentOS上yum安装屏幕,然后通过putty或其他软件在你的shell类型屏幕上访问你的服务器。它将打开屏幕[0]在腻子。做好你的工作。你可以在同一个putty会话中创建更多的screen[1], screen[2]等。
你需要知道的基本命令:
启动屏幕
屏幕
创建下一个屏幕
ctrl + a + c
移动到您创建的下一个屏幕
ctrl + a + n
要分离
ctrl + a + d
在工作期间关闭腻子。下次当你登录通过putty类型
屏幕- r
重新连接到屏幕,您可以看到您的进程仍在屏幕上运行。要退出屏幕,输入#exit。
欲了解更多细节,请参阅男子界面。
其他回答
使用屏幕。它使用起来非常简单,就像终端的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.
就我个人而言,我喜欢“batch”命令。
$ batch
> mycommand -x arg1 -y arg2 -z arg3
> ^D
这将把它塞到后台,然后将结果邮寄给你。这是cron的一部分。
在基于debian的系统上(在远程机器上) 安装:
Sudo apt-get install tmux
用法:
tmux 运行您想要的命令
重命名会话:
按Ctrl+B然后$ 集名称
退出会话:
按Ctrl+B然后D
(这会留下tmux会话)。此时可以退出SSH。
当您需要再次返回/检查它时,启动SSH,并输入
Tmux附加session_name
它将带您回到tmux会话。
接受的回答建议使用nohup。我建议用pm2。使用pm2而不是nohup有很多优点,比如保持应用程序处于活动状态,维护应用程序的日志文件以及许多其他特性。要了解更多细节,请查看这个。
安装pm2需要下载npm。基于Debian的系统
sudo apt-get install npm
还有红帽公司
sudo yum install npm
或者你可以按照这些说明来做。 在安装npm之后,使用它来安装pm2
npm install pm2@latest -g
一旦完成,你可以开始你的应用程序
$ pm2 start app.js # Start, Daemonize and auto-restart application (Node)
$ pm2 start app.py # Start, Daemonize and auto-restart application (Python)
使用以下命令进行进程监控:
$ pm2 list # List all processes started with PM2
$ pm2 monit # Display memory and cpu usage of each app
$ pm2 show [app-name] # Show all informations about application
使用应用程序名称或进程id管理进程或同时管理所有进程:
$ pm2 stop <app_name|id|'all'|json_conf>
$ pm2 restart <app_name|id|'all'|json_conf>
$ pm2 delete <app_name|id|'all'|json_conf>
日志文件可以在
$HOME/.pm2/logs #contain all applications logs
二进制可执行文件也可以使用pm2运行。你得修改一下杰森的档案。将“exec_interpreter”:“node”修改为“exec_interpreter”:“none”。(请参阅属性部分)。
#include <stdio.h>
#include <unistd.h> //No standard C library
int main(void)
{
printf("Hello World\n");
sleep (100);
printf("Hello World\n");
return 0;
}
编译上述代码
gcc -o hello hello.c
在后台运行np2
pm2 start ./hello