Avoid race condition with Popen.send_signal

Adam Skutt askutt at gmail.com
Tue Jan 3 10:03:08 EST 2012


On Jan 3, 4:38 am, Jérôme <jer... at jolimont.fr> wrote:
> I have an application that can spawn a subprocess to play a beep. I want it
> to kill the subprocess when exiting.

Why?  You shouldn't need to send a signal to tell the process to
terminate: it should terminate when its stdin is closed or when it's
done playing the beep in the first place.  If it doesn't, I would find
a better way to play a beep in the first place.  What you're
attempting to do sounds superfluous and unnecessary.

The only thing you ought to need to do is ensure that the child
process is properly reaped if it terminates before your process
terminates.

> To do so, my close() method must
>
>   a/ Check if any subprocess has actually been launched (I store the Popen in
>   a variable called _beep_process. If Popen has not been called, the variable
>   is init to 0 and the call to send_signal will fail.)
>
>   b/ Check if the process is still alive using Popen.poll() and returncode
>   (otherwise, I might kill a new process)
>
>   c/ Catch the exception in case the process would be dead since the last
>   check (otherwise, I might get an error from send_signal)
>

Steps a and c are all that are necessary under standard SIGCHLD
handling.  However, all of this should be entirely unnecessary in the
first place.  Plus, I have a hard time imagining why something like
'gtk.gdk.beep()' isn't adequate for your needs anyway.

> For instance, Popen.send_signal() should not be able to send a signal to a
> subprocess that has already returned, should it ? Is there any good reason
> for allowing it to do so ? If not, it would spare me check b/ in this example.
>

The problem is being able to distinguish "process is a zombie" from
"process doesn't exist" which both return ESRCH.  This is certainly
possible with careful coding but I'm not sure I would bother except in
the simplest programs.  Too many libraries do too many questionable
things with signal handlers so I find it much safer and easier just to
avoid the damn things whenever possible.

Adam



More information about the Python-list mailing list