介绍一下 linux命令 nohup 和 & 使得程序在后台运行

运行命令时想要直接挂在后台 在命令后面加&  这样命令就挂在后台运行了 就算按Ctrl+c  也不会中断 但是程序输出会打印在终端

command &

        比如:python3 del_instruments.py& 

        执行命令后会返回一个进程号:如下:[1] 78272            其中,pid=78272

        使用jobs命令可以查看当前后台运行的进程如:[1]+  Running                 python3 del_instruments.py &

        想关闭时kill -9 78272就可以了

(env1) livia:script apple$ python3 del_instruments.py&
[1] 78272
(env1) livia:script apple$ jobs
[1]+  Running                 python3 del_instruments.py &

 ‘command &’ 当关闭窗口或者退出ssh 时,进程也会被关闭,如果想保持进程一直运行怎么办呢?

格式:

nohup command

该命令在缺省情况下会把标准输出到nohup.out文件中,也就是不会在终端输出标准输出(你的打印)

解释如下:

        nohup:no hang up 也就是不挂断的意思 命令可以将程序以忽略挂起信号的方式运行起来,就是即使退出ssh进程也不会挂断,但这个命令并没有后台运行的意思,和后台半毛钱关系没有,只是执行了一个命令,忽略挂起信号而已(注意ctrl+c可以强制退出)

如果想把程序放到后台运行,而且退出ssh也不挂断咋办呢?两者结合一下即可:

nohup command &

案例:

(env1) livia:script apple$ nohup python3 del_instruments.py &
[1] 78498
(env1) livia:script apple$ appending output to nohup.out

(env1) livia:script apple$ jobs
[1]+  Running                 nohup python3 del_instruments.py &
(env1) livia:script apple$

注意 :执行命令后会收到一条提示  appending output to nohup.out 要点击一下enter才算成功把命令放到后台运行哦  否则可能会失败

  

如果你还是不懂,没关系,看看大白话

区别:

command + &:就是在后台运行命令,会把print打印在终端,ctrl+c不可以终止进程,随着ssh退出或窗口关闭会关闭进程

nohup + command: 忽略挂起运行命令,不会把print打印在终端,Ctrl+c可以中断进程,随着ssh退出或者窗口关闭不会关闭进程

 nohup + command + &: 忽略挂起,在后台运行命令,不会把print打印在终端,随着ssh退出或者窗口关闭不会关闭进程,一般使用这个 

 转自:https://blog.csdn.net/weixin_40647516/article/details/103733853

原文地址:https://www.cnblogs.com/liushui-sky/p/13913521.html