我应该使用等待Popen吗

时间:2018-09-06 03:16:22

标签: python concurrency process signals fork

我正在subprocess.Popen函数中使用playStation来运行另一个进程,即媒体播放器来播放广播电台。但是,当我杀死父进程时,它不会停止,也不会被杀死。只是在按下CTRL-CCTRL-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

0 个答案:

没有答案