后台运行脚本

需求:很多时候我们会在 linux 服务器上执行 python 脚本,然而脚本程序执行的时间可能比较长,当耗时过长的情况下,我们使用 ssh 远程登录到 linux 服务器上容易造成超时自动断开连接,当用户注销时,终端会收到 hup(hangup)信号从而关闭其所有子进程,会导致正在执行中的 python 脚本被中断,为了解决这一问题,我们使用 nohup 命令并结合 & 解决此问题。

命令格式:​​nohup command &​

nohup 指:在忽略挂起信号的情况下运行给定的命令,以便在注销后命令可以在后台继续运行;nohup 并不支持后台运行,它是忽略内部的挂断信号,不挂断运行

& 指:后台运行,即将进程放到后台运行,这里的后台,其实指的是当前登陆终端的后台,如果在命令尚未执行完毕时就退出登陆,则此命令的执行会被中断。

那么,如果将 nohup 与 & 结合在一起使用,这样就可以不挂断的永久在后台执行。

命令示例:(将 test.py 输出的内容写入到 test.out 文件中)nohup python -u test.py 参数1 参数2 参数3 > test.out 2>&1 &

其中 “2>&1” 表示:将错误和输出都传到 test.out 文件中,默认状态只把输出输出到文件中

如果去掉末尾的 ‘&’ ,则表示此命令会在终端前台工作,所有输出的内容会写入到 test.out 文件。

实时查看 test.py 输出的内容:​​tail -f -n 20 test.out​

启动脚本

例如我要同时运行多个python脚本,可以这么创建一个start.sh

#!/bin/bash
cd ./middle_back_end/backend/
nohup python -u backend_today.py >/home/hanhan/InternShipProject/out/today.out 2>&1 &
nohup python -u backend_yestoday.py >/home/hanhan/InternShipProject/out/yestoday.out 2>&1 &
nohup python -u backend_getnums.py >/home/hanhan/InternShipProject/out/getnums.out 2>&1 &
cd /home/hanhan/InternShipProject/front_middle_end/backend/
nohup python -u backend.py >/home/hanhan/InternShipProject/out/flask.out 2>&1 &

然后在sh文件目录下,通过命令​​sh start.sh​​​运行脚本。然后我们看看是否运行成功:
运行命令​​​ps -ef | grep backend​​(因为我这边脚本名字中都有backend这个字眼),可以看到确实都在运行

[root@VM-90-225-centos /home/hanhan/InternShipProject]# ps -ef | grep backend
root 13618 1 8 14:26 pts/7 00:00:35 python -u backend_today.py
root 13619 1 8 14:26 pts/7 00:00:35 python -u backend_yestoday.py
root 13620 1 0 14:26 pts/7 00:00:00 python -u backend_getnums.py
root 13621 1 0 14:26 pts/7 00:00:00 python -u backend.py
root 13846 13621 0 14:26 pts/7 00:00:02 /usr/bin/python /var/www/html/InternShipProject/front_middle_end/backend/backend.py
root 24194 23153 0 14:33 pts/3 00:00:00 grep --color=auto backend

关闭脚本

将刚刚创建的几个进程一次性kill掉,创建stop.sh

#!/bin/sh
ps -ef |grep backend | grep -v grep | awk '{print $2}' | xargs kill -9

第一段前面两节不陌生,是查找某个进程,第三节的意思是过滤grep(一般调用前两节命令后显示的有两段数据,过滤的就是第二段无用的数据),第四节的意思是找出进程号
$2:表示第二个字段
print $2 : 打印第二个字段,第五节的意思是杀死找出的进程号.

然后在sh文件目录下,通过命令​​sh stop.sh​​​运行脚本。
最后再通过​​​ps -ef |grep backend​​命令观察,发现kill成功。