Using signal.alarm to terminate a thread
nick at craig-wood.com
Tue Nov 14 12:30:06 CET 2006
Adrian Casey <adrian.casey at internode.on.net> wrote:
> > Adrian Casey <adrian.casey at internode.on.net> wrote:
> > import os, pexpect, threading
> > def runyes():
> > print "Running yes command..."
> > pexpect.run('yes', timeout=5)
> > t = threading.Thread(target=runyes)
> > t.start()
> > t.join()
> The timeout parameter will not work in this case. If you run the sample
> code above, it will run forever.
The above runs just fine for me, stopping after 5 seconds. Did you
> The 'yes' command presents a class of command which can not be
> easily be handled by pexpect.
Worked for me under Debian/testing.
> As far as I know, mixing threads and signals is OK provided the
> parent creates the alarm.
There are so many pitfalls here that I advise you not to try. From
the linuxthreads FAQ
J.3: How shall I go about mixing signals and threads in my program?
The less you mix them, the better. Notice that all pthread_*
functions are not async-signal safe, meaning that you should not
call them from signal handlers. This recommendation is not to be
taken lightly: your program can deadlock if you call a pthread_*
function from a signal handler!
The only sensible things you can do from a signal handler is set a
global flag, or call sem_post on a semaphore, to record the delivery
of the signal. The remainder of the program can then either poll the
global flag, or use sem_wait() and sem_trywait() on the semaphore.
Another option is to do nothing in the signal handler, and dedicate
one thread (preferably the initial thread) to wait synchronously for
signals, using sigwait(), and send messages to the other threads
Note also that the signal can be delivered to any thread which
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick
More information about the Python-list