在 Linux shell 中,我可以运行此命令来终止由 python 脚本创建的每个进程(由 sudo python3 server.py
启动):
sudo kill -9 `ps -ef | grep server.py |grep -v "grep"|awk '{{print $2}}'
我想将其添加到我的脚本中,并在开始时结束任何先前的脚本进程,以避免出现套接字“地址已在使用中”错误。
这是我的代码:
try:
application.listen(port=63)
except OSError as e:
if e.errno == errno.EADDRINUSE:
cmd = 'sudo kill -9 `ps -ef | grep server.py |grep -v "grep"|awk \'{{print $2}}\'`'
print('try to kill previous',cmd)
import os
os.system(cmd)
问题是这也会杀死新进程,因为它也是由相同的关键字启动的。
如何避免这种情况?
最佳答案
不必按名称杀死程序,您可以简单地 终止正在监听端口 63 的程序。
以下命令为您提供监听端口 63 的程序的 PID
netstat --numeric-ports --listening --program | awk '{if (match($4, ":63$")) { split($NF, a, "/"); print a[1];}}'
或者更简短的形式:
netstat -nlp | awk '{if (match($4, ":63$")) {split($NF, a, "/"); print a[1];}}'
将所有内容粘合在一起,杀死监听端口 63 的程序的命令如下:
sudo kill -9 `netstat -nlp | awk '{if (match($4, ":63$")) {split($NF, a, "/"); print a[1];}}'`
解释如下:
netstat -nlp
输出监听某些端口的所有程序,而不解析端口名称。
因此人们会得到这样的结果:
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 127.0.0.1:9000 0.0.0.0:* LISTEN 2096/php-fpm.conf)
tcp 0 0 127.0.0.1:63 0.0.0.0:* LISTEN 2263/memcached
tcp 0 0 0.0.0.0:36815 0.0.0.0:* LISTEN 1748/rpc.statd
....
awk命令的含义如下:
awk '{
# check if field "Local Address" ends with ":63"
if (match($4, ":63$")) {
# split the field "PID/Program name"
# into the array a based on delimiter "/"
split($NF, a, "/");
# print the PID
print a[1];
}
}'
关于python - 通过 shell 杀死进程而不杀死自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18468045/