SIGCHLD, fork, listen

Donn Cave donn at u.washington.edu
Thu Sep 23 14:11:03 EDT 1999


Quoth bill <bill at rfa.org>:
| I'm trying to set up a fairly "simple"
| server that listens for a socket connection,
| forks off a process and goes back to listening.
| This works fine for multiple clients, except
| I get zombies.  I try redefining SIGCHLD as
| SIG_IGN, but this doesn't work (as apparently
| is what's expected under POSIX).  I then
| try redefining it with my own function that
| includes a WAIT.  Fine, except "listen"
| doesn't get signalled when the child process
| dies, only when the next socket connection
| occurs.  (which could be hours later, not
| good).

This sounds like your platform "restarts" the accept() system call
after an interrupt.  That's kind of a feature for C programmers,
because otherwise they have to check for EINTR after this kind of
system call and restart it themselves.  Python programmers do too,
for that matter, but your Python signal handlers don't execute in
a kind of parallel Python thread, they wait for the next chance at
the interpreter.  That chance is going to come when the EINTR hit -
unless the system call restarts on its own.

I don't like SIGCHLD in C programs, and it's even less useful in
Python.  In your shoes, I would probably just run waitpid() when
the opportunity arises in the accept/fork loop, and live with the
occasional zombie processes.

If you can't stand them, you can get rid of them with a double fork().
The forked child immediately forks again while its parent calls waitpid().
The first forked process exits, and the parent's waitpid() returns, right
away.  That leaves an orphaned process whose parent reverts to 1 ("init").

In C, on at least some UNIX platforms that support X/Open standard signal
operations, you can use sigaction(2) with SIGCHLD and a SA_NOCLDWAIT flag
to just dispense with the zombie system.  Haven't actually used this
myself, and I don't know how widely it's supported.  It's not an option
in the standard Python signal module.

	Donn Cave, University Computing Services, University of Washington
	donn at u.washington.edu




More information about the Python-list mailing list