你的位置:首页 > 软件开发 > 操作系统 > nohup/setsid/ 让进程在后台可靠运行

nohup/setsid/ 让进程在后台可靠运行

发布时间:2017-08-16 15:00:15
当用户注销(logout)或者网络断开时,终端会收到 HUP(hangup)信号从而关闭其所有子进程。因此,我们的解决办法就有两种途径:要么让进程忽略 HUP 信号,要么让进程运行在新的会话里从而成为不属于此终端的子进程。(hangup 名称的来由:在 Unix 的早期版本中,每 ...

 

当用户注销(logout)或者网络断开时,终端会收到 HUP(hangup)信号从而关闭其所有子进程。因此,我们的解决办法就有两种途径:要么让进程忽略 HUP 信号,要么让进程运行在新的会话里从而成为不属于此终端的子进程

(hangup 名称的来由:在 Unix 的早期版本中,每个终端都会通过 modem 和系统通讯。当用户 logout 时,modem 就会挂断(hang up)电话。 同理,当 modem 断开连接时,就会给终端发送 hangup 信号来通知其关闭所有子进程)

 

1.nohup:让提交的命令忽略 hangup 信号

nohup 的帮助信息:

$ nohup --help
Usage: nohup COMMAND [ARG]... or: nohup OPTION
Run COMMAND, ignoring hangup signals. --help display this help and exit --version output version information and exitIf standard input is a terminal, redirect it from an unreadable file.If standard output is a terminal, append output to 'nohup.out' if possible,'$HOME/nohup.out' otherwise.If standard error is a terminal, redirect it to standard output.To save output to FILE, use 'nohup COMMAND > FILE'.

 

使用:在要处理的命令前加上 nohup 即可,标准输出和标准错误缺省会被重定向到 nohup.out 文件中。一般我们可在结尾加上"&"来将命令同时放入后台运行,也可用"> filename"来更改缺省的重定向文件路径。

nohup ping www.baidu.com &nohup python train_model.py > console.log &

 

2.setsid:在新session执行命令(使进程不属于接受 HUP 信号的终端的子进程,那么就不会受到 HUP 信号的影响)

setsid的帮助信息:

$ setsid --helpUsage: setsid [options] <program> [arguments ...]Run a program in a new session.Options: -c, --ctty  set the controlling terminal to the current one -w, --wait  wait program to exit, and use the same return -h, --help  display this help and exit -V, --version output version information and exit

 

使用:

setsid ping www.ibm.com &

 

另外,查看进程并停止:

$ ps -ef | grep pingabby  3899 1632 0 14:39 ?  00:00:00 ping www.baidu.comabby  4038 3907 0 14:43 pts/20 00:00:00 grep --color=auto ping$ kill -9 3899

 

参考:

Linux 技巧:让进程在后台可靠运行的几种方法

 

原标题:nohup/setsid/ 让进程在后台可靠运行

关键词:进程

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。