Linux下优雅的让程序后台运行

来源:互联网 发布:vscode 运行npm命令 编辑:程序博客网 时间:2024/05/29 04:54
Linux下优雅的让程序后台运行

  假设在终端上启动运行了一个程序,跑了几天,如果不小心把terminal关了,那么程序就会终止,这是SIGHUP信号的原因,即使通过bg置为后台运行同样会如此,应该让程序成为一个daemon,步骤如下:

法1

1.Ctrl+z 暂停程序的运行,可以看到程序的作业号,假设为1;
2.bg %1 置为后台运行;
3. disown -h %1 使其不受终端关闭的影响。


=> The disown command on ksh shell causes the shell not to send a HUP signal to each given job, or all active jobs if job is omitted, when a login shell terminates.

=>The disown command on bash shell can either remove jobs or causes the shell not to send a HUP signal to each given job or all jobs.


实例:

./main.py 之前是终端上正常运行的普通程序。


按上面操作之后,通过 ps -ef | awk '$3 == 1' 命令可以看到程序变成了daemon.



法二:

nohup your_command > /dev/null 2>&1 &

  1. nohup:表示所属终端关闭后,进程不会死掉;
  2. > /dev/null :标准输出重定向到 /dev/null (a dummy device that does not record any output).
  3. 2>&1 :标准出错重定向到标准输出,也到/dev/null
  4. 最后的& :后台任务


参考:

1.http://stackoverflow.com/questions/625409/how-do-i-put-an-already-running-process-under-nohup

2.http://stackoverflow.com/questions/4797050/how-to-run-process-as-background-and-never-die

阅读全文
0 0
原创粉丝点击