nohup 使用与进阶
nohup
命令是Linux上运行程序必学的命令之一。
使用该命令运行程序可以忽略挂断信号。一般最后配合&,使程序在后台执行,并且在终端退出后不打断程序执行。
nohup <command> &
nohup
运行时返回程序运行的进程号,命令默认输出到当前目录下的nohup.out
文件。
$ nohup python temp.py &[1] 31323$ nohup: ignoring input and appending output to 'nohup.out'[1]+ Done nohup python temp.py
正常结束时会给出Done
。
指定输入输出
$ nohup python temp.py >temp.log 2>&1 &[1] 31430$ [1]+ Done nohup python temp.py < /dev/null > temp.log 2>&1
指定输出到temp.log
文件。
2 - stderr
指标准错误输出,1 - stdout
指标准输出,&1表示1输出通道,2>&1
表示将2重定向到1,即将标准错误输出传递给标准输出。
$ cat temp.lognohup: ignoring input------
查看temp.log
文件,发现多了一行ignoring input
。
为了避免产生此消息,给定输入,但是此程序本身不需要输入,给空输入的方法是引用/dev/null
。
$ nohup python temp.py </dev/null >temp.log 2>&1 &
实时输出
nohup
默认使用缓存,不实时输出结果,为了让结果及时的输出,可以将缓存强制设为0。
stdbuf
命令能够修改与程序关联的三个标准I/O流的缓冲操作,i - input
,o - output
,e - error
。
python自身也有缓存机制,使用-u参数不使用缓存。
nohup stdbuf -i0 -o0 -e0 python -u temp.py < /dev/null > temp.log 2>&1 &
停止运行
在运行程序时,nohup
会返回进程号,因此可以使用kill
命令结束该进程。
$ nohup stdbuf -i0 -o0 -e0 python -u temp.py < /dev/null > temp.log 2>&1 &[1] 9243$ kill -9 9243$ [1]+ Killed nohup stdbuf -i0 -o0 -e0 python -u temp.py < /dev/null > temp.log 2>&1
kill -9
代表的信号是SIGKILL
,表示进程被终止,需要立即退出,该信号不会被系统阻塞。
一般我们不会记住进程号,使用top
命令可以查看目前正在运行的进程,找到对应进程号,但是这种方式较为麻烦。
使用ps
命令可以轻松的找到进程号。
$ ps -aux | grep "python -u temp.py" biodb 15705 0.0 0.0 32372 9232 pts/5 S 16:32 0:00 python -u temp.pybiodb 15764 0.0 0.0 14428 1040 pts/5 S+ 16:33 0:00 grep --color=auto python -u temp.py
a : 显示所有程序, u : 以用户为主的格式来显示,x : 显示所有程序,不区分终端机。
第一个进程即为正在运行的程序,第二个进程是grep
自己的进程。
随后使用kill
:
$ kill -9 15705$ [1]+ Killed nohup stdbuf -i0 -o0 -e0 python -u temp.py < /dev/null > temp.log 2>&1
我
我是 SSSimon Yang,关注我,用code解读世界