linux nohup命令

时间:2022-02-15 21:29:31

nohup 命令

用途:不挂断地运行命令。如果你正在执行一个job,并且你希望在退出帐户/关闭终端之后继续运行,可以使用nohup命令。nohup就是不挂起的意思( no hang up)。

语法:nohup Command [ Arg … ] [ & ]

描述:nohup 命令运行由 Command 参数和任何相关的 Arg 参数指定的命令,忽略所有挂断(SIGHUP)信号。在注销后使用 nohup 命令运行后台中的程序。要运行后台中的 nohup 命令,添加 & ( 表示”and”的符号)到命令的尾部。

无论是否将 nohup 命令的输出重定向到终端,输出都将附加到当前目录的 nohup.out 文件中。如果当前目录的 nohup.out 文件不可写,输出重定向到 $HOME/nohup.out 文件中。如果没有文件能创建或打开以用于追加,那么 Command 参数指定的命令不可调用。如果标准错误是一个终端,那么把指定的命令写给标准错误的所有输出作为标准输出重定向到相同的文件描述符。

=======测试

[root@rhel7 tmp]# pwd
/tmp
[root@rhel7 tmp]# ls
[root@rhel7 tmp]# nohup ping 127.0.0.1 &
[]
[root@rhel7 tmp]# nohup: ignoring input and appending output to ‘nohup.out’ [root@rhel7 tmp]# ls
nohup.out
[root@rhel7 tmp]# tail -f nohup.out --关闭当前连接,重新再打开一个ssh连接,使用tail -f nohup.out命令可以看到ping命令一直在执行
bytes from 127.0.0.1: icmp_seq= ttl= time=0.077 ms
bytes from 127.0.0.1: icmp_seq= ttl= time=0.044 ms
bytes from 127.0.0.1: icmp_seq= ttl= time=0.129 ms
bytes from 127.0.0.1: icmp_seq= ttl= time=0.084 ms
bytes from 127.0.0.1: icmp_seq= ttl= time=0.085 ms
bytes from 127.0.0.1: icmp_seq= ttl= time=0.085 ms
bytes from 127.0.0.1: icmp_seq= ttl= time=0.079 ms
bytes from 127.0.0.1: icmp_seq= ttl= time=0.078 ms
bytes from 127.0.0.1: icmp_seq= ttl= time=0.078 ms
bytes from 127.0.0.1: icmp_seq= ttl= time=0.083 ms
bytes from 127.0.0.1: icmp_seq= ttl= time=0.043 ms
bytes from 127.0.0.1: icmp_seq= ttl= time=0.084 ms
^C
[root@rhel7 tmp]#

指定输出到lxjtest.log。如果不指定,则输出到nohup.out文件

[root@rhel7 tmp]# nohup ping 127.0.0.1 >lxjtest.log &
[]
[root@rhel7 tmp]# nohup: ignoring input and redirecting stderr to stdout [root@rhel7 tmp]# ls
lxjtest.log nohup.out
[root@rhel7 tmp]# tail -f lxjtest.log
PING 127.0.0.1 (127.0.0.1) () bytes of data.
bytes from 127.0.0.1: icmp_seq= ttl= time=0.039 ms
bytes from 127.0.0.1: icmp_seq= ttl= time=0.073 ms
bytes from 127.0.0.1: icmp_seq= ttl= time=0.043 ms
bytes from 127.0.0.1: icmp_seq= ttl= time=0.043 ms
bytes from 127.0.0.1: icmp_seq= ttl= time=0.044 ms
bytes from 127.0.0.1: icmp_seq= ttl= time=0.044 ms
bytes from 127.0.0.1: icmp_seq= ttl= time=0.043 ms
bytes from 127.0.0.1: icmp_seq= ttl= time=0.079 ms
bytes from 127.0.0.1: icmp_seq= ttl= time=0.079 ms
bytes from 127.0.0.1: icmp_seq= ttl= time=0.086 ms
^C
[root@rhel7 tmp]#

In earlier versions of the bash shell, background processes were also killed when the shell they were started from was terminated. To prevent that, the process could be started with the  nohup  command in front of it. Using  nohup  for this purpose is no longer needed in RHEL 7. (RHEL7版本可以不使用nohup命令)

[root@rhel7 tmp]# ping 192.168.1.111 > lxjtest2.log &
[]
[root@rhel7 tmp]# jobs
[]+ Running ping 192.168.1.111 > lxjtest2.log &
[root@rhel7 tmp]#