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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值