時如何讓蟒蛇子進程的標準輸出,我有以下簡單的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