简体   繁体   中英

Capture Ctrl-C Signal And Wait For Subprocess

I have a bit of python code in which I call a subprocess, and within the python script I want to capture the SIGINT signal, and wait for the subprocess to finish. Currently what I have kills the process when I ctrl-c. Any way to tell python to wait for the process to finish? Although I want to wait for the process, I do want the script to die after the process finishes, not sure if theres a way to do this.

import subprocess as sp  
from celery.platforms import signals 

def outer_fun(): 
    p = None

    def signal_handler(signum, frame): 
        if p != None: 
            p.wait()

signals['INT'] = signal_handler 

p = sp.Popen(['sleep','30'])
result = p.wait() 

print result[0]

outer_fun()

Found a solution, although not what I expected it works! With the preexec_fn=os.setpgrp option the ctrl c signal is not sent to the subprocess.

p = sp.Popen(cmd, preexec_fn=os.setpgrp)

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