[Python-Dev] Signal-resistant code (was: Two random and nearly unrelated ideas)

Oren Tirosh oren-py-d@hishome.net
Wed, 4 Sep 2002 21:51:31 +0300

On Wed, Sep 04, 2002 at 11:04:27AM -0700, Brett Cannon wrote:
> [Oren Tirosh]
> <snip>
> >
> > Not before all all Python I/O calls are converted to be EINTR-safe.
> what is EINTER-safe?

When an I/O operation is interrupted by an unmasked signal it returns 
with errno==EINTR.  The state of the file is not affected and repeating
the operation should recover and continue with no loss of data.

Here is an EINTR-safe version of read:

ssize_t safe_read(int fd, void *buf, size_t count) {
	ssize_t result;
	do {
		result = read(fd, buf, count);
	} while (result == -1 && errno == EINTR);
	return result;

When exposing the C I/O calls to Python you can either:

1. Use EINTR-safe I/O and hide this from the user.
2. Pass on EINTR to the user.

Python currently does #2 with a big caveat - the internal buffering 
of functions like file.read or file.readline is messed up and cannot be 
cleanly restarted. This makes signals unusable for delivery of asynchronous 
events in the background without affecting the state of the main program.