Linux中的nohup和& | Linux指令后台执行

经常看到下面这样的指令:

nohup command... &

这个指令的作用是:执行一个可以一直在后台运行的指令

通俗解释:

nohup:指令可以在退出会话后继续执行(退出SSH连接后继续执行)
&:指令在后台执行

nohup + &:把指令放在后台执行,并且在退出会话后还能继续执行

注意:可以在后台执行,不代表在退出会话后还可以继续执行

详细解释:

nohup
意思是:no hangup,忽略HUP信号,让指令在当前会话结束或者当前用户退出登录后可以继续运行;
并且将当前指令的输出内容添加到当前目录或者home目录的"nohup.out"文件中。

用户退出终端不会终止指令的执行,但是如果执行的指令阻塞当前IO,那么终端将无法响应用户的输入。

[root@centos8 ~]# nohup ping baidu.com
nohup: ignoring input and appending output to 'nohup.out'
^C[root@centos8 ~]# 

#上方指令执行后,终端将无法交互,需要按下Ctrl + C来中断执行
#查看nohup.out
[root@centos8 ~]# cat nohup.out 
PING baidu.com (220.181.38.148) 56(84) bytes of data.
64 bytes from 220.181.38.148 (220.181.38.148): icmp_seq=1 ttl=49 time=30.9 ms
64 bytes from 220.181.38.148 (220.181.38.148): icmp_seq=2 ttl=49 time=30.9 ms
64 bytes from 220.181.38.148 (220.181.38.148): icmp_seq=3 ttl=49 time=30.9 ms
64 bytes from 220.181.38.148 (220.181.38.148): icmp_seq=4 ttl=49 time=30.9 ms

--- baidu.com ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 6ms
rtt min/avg/max/mdev = 30.877/30.903/30.928/0.125 ms
[root@centos8 ~]# 

&
让当前指令在后台运行,不会阻塞当前用户交互。并且会在指令执行完成后,立即返回到前台,同时输出后台执行时的PID和指令输出的内容。

但是用户退出终端后,会停止这个后台执行的指令。

[root@centos8 ~]# cat nohup.out &
[2] 63498
[root@centos8 ~]# PING baidu.com (220.181.38.148) 56(84) bytes of data.
64 bytes from 220.181.38.148 (220.181.38.148): icmp_seq=1 ttl=49 time=30.9 ms
64 bytes from 220.181.38.148 (220.181.38.148): icmp_seq=2 ttl=49 time=30.9 ms

--- baidu.com ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 3ms
rtt min/avg/max/mdev = 30.876/30.893/30.910/0.017 ms

[2]-  Done                    cat nohup.out
[root@centos8 ~]# 

cat会进入后台执行,执行完成后立刻返回到前台,并提示后台执行时的PID和输出内容(上方的63498)

参考:

How to use Nohup in Linux

猜你喜欢

转载自blog.csdn.net/djzhao627/article/details/123557023