我正在subprocess.Popen
函数中使用playStation
来运行另一个进程,即媒体播放器来播放广播电台。但是,当我杀死父进程时,它不会停止,也不会被杀死。只是在按下CTRL-C
,CTRL-Z
或发送SIGKILL
后卡住了。通常,应立即将其杀死。但不是。
我觉得我确实犯了一个或多个错误。其中之一也许我不希望等待subprocess.Popen
运营的媒体播放器,因为它播放广播电台直到我杀死孩子为止。我应该等吗?如果是这样,怎么在哪里?
如果我在return p
之前等待,它将卡住。
我尝试简化代码,
def playStation(stationAddress):
# if there is a media player being run, kill it for new one
killMPlayer = "killall mplayer"
os.system(killMPlayer)
radioName = 'mplayer ' + '-playlist ' + stationAddress
p = subprocess.Popen(radioName.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
## the return value is not used I have added it ,maybe necessary
return p
arr = [
'radio ip address:port 1',
'radio ip address:port 2',
'radio ip address:port 3',
'radio ip address:port 4',
.
.
.
.
.
there are more but just simplicity 4 is enough
]
counter = 0
try:
while True:
signal.signal(signal.SIGCHLD, signal.SIG_IGN)
pid = os.fork()
if pid == 0:
playStation(arr[counter])
### normally playStation does work, control is takeovered by '''mplayer''' !!!!
exit(0)
else:
### wait until rotary encoder(switcher) is turned
GPIO.wait_for_edge(CLOCKPIN, GPIO.FALLING)
sleep(0.5)
### stop current child to create new child
### stop currently playing radio station to change to new station
os.kill(pid, signal.SIGTERM)
#os.waitpid(pid, 0)
# prevent index out of bound
if rotary_encoder_turned_left:
counter = counter - 1
if counter < 0:
counter = 4
elif rotary_encoder_turned_right:
counter = counter + 1
if counter > 4:
counter = 0