我正在尝试编写一个运行并杀死另一个python脚本的简单python服务器。我遇到的问题是kill命令被发出没有错误,但不会杀死进程。我用'kill -INT pid'手动尝试了没有任何结果。
该命令在shell中运行,但不在python中运行。我正在进行“软”杀戮,因为脚本控制了一个灯光并且'kill -9'没有关闭灯光。
注意:脚本在yocto-distr
上运行import socket, subprocess
srv = socket.socket()
srv.bind(('', 1340))
srv.listen(3)
while 1:
connection, address = srv.accept()
data = int(connection.recv(1024))
if data == 0:
ps_id = subprocess.check_output('ps|grep python\ /home/root/python/backlight_mod.py', shell=True)
ps_id = ps_id.split(' ')[2]
subprocess.call('kill -INT ' + str(ps_id), shell=True)
print 'Terminated'
elif data == 1:
subprocess.call('python ~/python/backlight_mod.py &', shell=True)
connection.close()
'kill -l'的输出:
HUP INT QUIT ILL TRAP ABRT BUS FPE KILL USR1 SEGV USR2 PIPE ALRM TERM STKFLT CHLD CONT STOP TSTP TTIN TTOU URG XCPU XFSZ VTALRM PROF WINCH IO PWR SYS RTMIN RTMIN+1 RTMIN+2 RTMIN+3 RTMIN+4 RTMIN+5 RTMIN+6 RTMIN+7 RTMIN+8 RTMIN+9 RTMIN+10 RTMIN+11 RTMIN+12 RTMIN+13 RTMIN+14 RTMIN+15 RTMAX-14 RTMAX-13 RTMAX-12 RTMAX-11 RTMAX-10 RTMAX-9 RTMAX-8 RTMAX-7 RTMAX-6 RTMAX-5 RTMAX-4 RTMAX-3 RTMAX-2 RTMAX-1 RTMAX
答案 0 :(得分:1)
考虑@Petesh建议的os.kill,所以你的代码看起来像这样:
if data == 0:
ps_id = subprocess.check_output('ps|grep python\ /home/root/python/backlight_mod.py', shell=True)
ps_id = ps_id.split(' ')[2]
os.kill(pid, 3)
print 'Terminated'
还要考虑以下内容来提取pid:
p = subprocess.Popen(['ps', '-A'], stdout = subprocess.PIPE)
out, err = p.communicate()
for process in out.splitlines():
if 'backlight_mod.py' in process:
pid = int(process.split(None, 1)[0])
os.kill(pid, 3)