Avoid race condition with Popen.send_signal

Adam Skutt askutt at gmail.com
Mon Jan 2 20:19:09 EST 2012


On Jan 2, 6:09 pm, Jérôme <jer... at jolimont.fr> wrote:
> Hi all.
>
> When a subprocess is running, it can be sent a signal with the send_signal
> method :
>
> process = Popen( args)
> process.send_signal(signal.SIGINT)
>
> If the SIGINT is sent while the process has already finished, an error is
> raised :
>
>   File "/usr/lib/python2.7/subprocess.py", line 1457, in send_signal
>     os.kill(self.pid, sig)
> OSError: [Errno 3] Aucun processus de ce type
>
> To avoid this, I can check that the process is still alive :
>
> process = Popen( args)
> process.poll()
> if (None == process.returncode):
>     process.send_signal(signal.SIGINT)
>
> It makes safer, but there is still an issue if the process ends between
> poll() and send_signal().
>
> What is the clean way to avoid this race condition ?

The fundamental race condition cannot be removed nor avoided. Ideally,
avoid the need to send the subprocess a signal in the first place.  If
it cannot be avoided, then trap the exception.

Adam



More information about the Python-list mailing list