nohup命令
nohup是“no hang up”的缩写形式。nohup命令有如下几种用法。
- 运行一个进程,且退出terminal/shell不影响其运行,但可以使用
ctrl+z
终止这个进程。 - 后台运行一个进程,退出terminal/shell不影响其运行,使用
ctrl+z
无法终止该进程,需使用kill命令终止该进程。
用法
查看nohup版本
leinao@ubuntu:~$ nohup --version
nohup (GNU coreutils) 8.25
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Written by Jim Meyering.
运行进程
#语法形式
nohup command
创建一个ping进程为例,默认将生成一个nohup.out文件存储输出结果,输出结果将会实时写入nohup.out文件。
leinao@ubuntu:~$ nohup ping baidu.com
nohup: ignoring input and appending output to 'nohup.out'
# 输出结果重定向至某个文件,使用>符号
leinao@ubuntu:~$ nohup ping baidu.com > test.txt
nohup: ignoring input and redirecting stderr to stdout
leinao@ubuntu:~$ cat test.txt
PING baidu.com (39.156.69.79) 56(84) bytes of data.
64 bytes from 39.156.69.79: icmp_seq=1 ttl=42 time=70.5 ms
64 bytes from 39.156.69.79: icmp_seq=2 ttl=42 time=67.4 ms
64 bytes from 39.156.69.79: icmp_seq=3 ttl=42 time=68.9 ms
64 bytes from 39.156.69.79: icmp_seq=4 ttl=42 time=66.9 ms
64 bytes from 39.156.69.79: icmp_seq=5 ttl=42 time=67.0 ms
64 bytes from 39.156.69.79: icmp_seq=6 ttl=42 time=67.0 ms
64 bytes from 39.156.69.79: icmp_seq=7 ttl=42 time=67.5 ms
64 bytes from 39.156.69.79: icmp_seq=8 ttl=42 time=67.0 ms
64 bytes from 39.156.69.79: icmp_seq=9 ttl=42 time=67.0 ms
leinao@ubuntu:~$ pgrep -a ping
273925 ping baidu.com
后台运行进程
#语法形式
nohup command &
leinao@ubuntu:~$ nohup ping baidu.com &
[2] 293515
leinao@ubuntu:~$ nohup: ignoring input and appending output to 'nohup.out'
# kill命令可终止该进程
kill -9 293515
异常情况的处理
- nohup运行python命令时输出的nohup.out文件为空怎么处理?
python命令后加-u
参数。
nohup python -u train.py --use-cuda --iters 200 --dataset coco --data-dir /home/leinao/data/coco2017 &