时如何让蟒蛇子进程的标准输出,我有以下简单的Python脚本:receving SIGUSR2/SIGINT
import os, subprocess,signal,sys
import time
out = None
sub = None
def handler(signum,frame):
print("script.py: cached sig: %i " % signum)
sys.stdout.flush()
if sub is not None and not sub.poll():
print("render.py: sent signal to prman pid: ", sub.pid)
sys.stdout.flush()
sub.send_signal(signal.SIGTERM)
sub.wait() # deadlocks....????
#os.kill(sub.pid, signal.SIGTERM) # this works
#os.waitpid(sub.pid,0) # this works
for i in range(0,5):
time.sleep(0.1)
print("script.py: cleanup %i" % i)
sys.stdout.flush()
sys.exit(128+signum)
signal.signal(signal.SIGINT, handler)
signal.signal(signal.SIGUSR2, handler)
signal.signal(signal.SIGTERM, handler)
sub = subprocess.Popen(["./doStuff.sh"], stderr = subprocess.STDOUT)
sub.wait()
print("finished script.py")
doStuff.sh
#!/bin/bash
function trap_with_arg() {
func="$1" ; shift
for sig ; do
trap "$func $sig" "$sig"
done
}
pid=False
function signalHandler() {
trap - SIGINT SIGTERM
echo "doStuff.sh chached sig: $1"
echo "doStuff.sh cleanup: wait 10s"
sleep 10s
# kill ourself to signal calling process we exited on SIGINT
kill -s SIGINT $$
}
trap_with_arg signalHandler SIGINT SIGTERM
trap "echo 'doStuff.sh ignore SIGUSR2'" SIGUSR2
# ignore SIGUSR2
echo "doStuff.sh : pid: $$"
echo "doStuff.sh: some stub error" 1>&2
for i in {1..100}; do
sleep 1s
echo "doStuff.sh, rendering $i"
done
当我将在推出的过程一个终端通过 python3 scripts.py &
一个信号与kill -USR2 -$!
脚本捕获到SIGINT,并在永远等待,ps -uf
显示以下内容:
user 27515 0.0 0.0 29892 8952 pts/22 S 21:56 0:00 \_ python script.py
user 27520 0.0 0.0 0 0 pts/22 Z 21:56 0:00 \_ [doStuff.sh] <defunct>
请注意,doStuff.sh
可以正确处理SIGINT并退出。
我还想调用handler
时获得标准输出吗?如何正确地做到这一点?
非常感谢!
我无法重现行为(你的操作系统,shell,python版本是什么?)。你能提供一个虚拟的'dostuff.py'作为例子吗?为什么使用' - $!'而不是'$!' - 前者可能会将信号发送给整个进程组? – jfs
我发送给整个进程组,因为我在集群上运行它,它向整个进程组发送SIGUSR2信号。 – Gabriel
我更新了答案,并提供了doStuff.sh。你可以在你的机器上试试这个,在我的这个死锁给出了如上所示的进程列表输出 – Gabriel