简体   繁体   中英

Process not terminating

I am trying to run all mp3 files in the background by creating a process using the multiprocessing library.

import os
import subprocess
from multiprocessing import Process

def music_player():

    music_folder = "/home/pi/Music/"
    files = os.listdir(music_folder)
    for mp3_file in files:
        print("playing " + mp3_file)
        p = subprocess.Popen(["omxplayer","-o","local",music_folder+mp3_file],
                          stdout = subprocess.PIPE,
                          stdin = subprocess.PIPE,
                          stderr = subprocess.PIPE)
        print(p)
        print(p.poll())
        print(p.pid)
        p.wait()



p = Process(target = music_player)
print(p, p.is_alive())
p.start()
print(p.pid)
print(p, p.is_alive())
command = raw_input()
if(command == "stop"):
    print("terminating...")
    p.terminate()
    print(p, p.is_alive())
    print(p.exitcode)  

After entering the "stop" command the code exits but the music is still running and on executing ps I see 2 process of omxplayer which I then have to manually kill through kill <pid> to make the music stop.

I previously tried using the subprocess library and killing the process using kill() and terminate() but the same issue occurred.

First observation, you don't need the multiprocessing module for what you're doing here. subprocess is for creating and managing processes which will run other scripts and programs; multiprocessing is for creating and managing processes which will be calling code which is already internal to your (parent) script.

I suspect that your seeing the effect of buffering. By the time you kill this process it's already buffered a significant amount of music out to the hardware (or even the OS buffers for the device).

What happens if you start the same program omxplayer from your shell, but in the background (as the & token to the end of your Unix shell command line to push a program into the background). Then use the kill command on that process and see if you see the same results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM