KeyboardInterrupt eats my error and then won't be caught

Philip Semanchuk philip at
Thu Jun 18 23:19:09 EDT 2009

Hi all,
I need help understanding how Python deals with Ctrl-C.

A user has reported a bug in my posix_ipc module. When a Python app is  
waiting to acquire an IPC semaphore and the user hits Ctrl-C, my code  
should return a custom error indicating that the semaphore wait was  
interrupted by a signal.

However, the caller never sees the error I set. Instead they get a  
KeyboardInterrupt that refuses to be caught by try/except. Here's a  
sample program that demonstrates the problem when run from the command  

# -----------------------------------
import posix_ipc

sem = posix_ipc.Semaphore(None, posix_ipc.O_CREX)

    sem.acquire()   # User hits Ctrl + C while this is waiting
    print "********* I caught it!"

# -----------------------------------

I expected that code to raise a posix_ipc.Error with the text, "The  
wait was interrupted by a signal" which would then be trapped by the  
except statement which would print the "I caught it!" message.

Instead a KeyboardInterrupt error is propagated up to the interpreter  
and the process is killed as if the try/except wasn't there at all.

I have verified that the C function sem_wait() returns -1 (failure),  
that errno is set to EINTR and that my detects that properly. So far,  
so good. PyErr_Occurred() returns NULL at that point. So my code calls  
PyErr_SetString() to set a custom error for the caller and returns  
NULL. It's apparently at some point after that that the  
KeyboardInterrupt error is being set.

If I substitute my sysv_ipc module for posix_ipc (very similar to  
posix_ipc but uses Sys V semaphores instead of POSIX), I get the same  

I see this w/Python 2.5 under OS X and also w/Python 2.5 under Ubuntu  

If anyone wants to look at my C code, the relevant case statement is  
on line 555 of posix_ipc_module.c.

Any suggestions would be appreciated.


More information about the Python-list mailing list