Linux 让进程在后台运行-nohup命令

在工作中,经常需要执行一些耗时较长的任务,但会因为本地终端关闭或网络断开连接,导致任务中途执行失败。

可以使用:
nohup 命令 & 来实现命令后台稳定运行,不受本地终端干扰

一、原理
当用户注销(logout)或者网络断开时,终端会收到 HUP(hangup)信号从而关闭其所有子进程。
nohup 的用途就是让提交的命令忽略 hangup 信号,先看一下 nohup 的帮助信息:

NOHUP(1)                         User Commands                        NOHUP(1)

NAME
       nohup - run a command immune to hangups, with output to a non-tty

SYNOPSIS
NOHUP(1)                         User Commands                        NOHUP(1)

NAME
       nohup - run a command immune to hangups, with output to a non-tty

SYNOPSIS
NOHUP(1)                         User Commands                        NOHUP(1)

NAME
       nohup - run a command immune to hangups, with output to a non-tty

SYNOPSIS
       nohup COMMAND [ARG]...
       nohup OPTION

DESCRIPTION
       Run COMMAND, ignoring hangup signals.

       --help display this help and exit

       --version
              output version information and exit

       If  standard input is a terminal, redirect it from /dev/null.  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就可以实现稳定运行,如果后台运行加上&就可以。
标准输出和标准错误会被默认输出到当前路径下的nohup.out文件中,如果需要重定向到其他文件,可以只用"> filename 2>&1"。
二、使用举例
例如使用jmeter进行长稳压测时,就不希望进程中途停掉,此时nohup就派上用场了。

$ nohup jmxx -n -t rec_post_forcast_mleap_constant.jmx -l ./zhangben_mleap_constant/zhangben_mleap_constant-5-5.j-1tl  -e -o ./zhangben_mleap_constant/zhangben_mleap_constant-5-5-1 &
[1] 12537
nohup: appending output to `nohup.out'

$ ps -ef | grep 12537
603      12537 12511  6 Apr29 ?        01:03:18 /usr/jdk1.8.0_51/bin/java -server -XX:+HeapDumpOnOutOfMemoryError -Xms1g -Xmx1g -XX:MaxMetaspaceSize=256m -XX:+UseG1GC -XX:MaxGCPauseMillis=100 -XX:G1ReservePercent=20 -Djava.security.egd=file:/dev/urandom -Duser.language=en -Duser.region=EN -jar /home/testknpub/wanwei/apache-jmeter-4.0/bin/ApacheJMeter.jar -n -t rec_post_forcast_mleap_constant.jmx -l ./zhangben_mleap_constant/zhangben_mleap_constant-5-5.j-1tl -e -o ./zhangben_mleap_constant/zhangben_mleap_constant-5-5-1
603      32616 32441  0 10:24 pts/0    00:00:00 grep 12537

猜你喜欢

转载自blog.csdn.net/a200822146085/article/details/89704480