Using signal.alarm to terminate a thread

Adrian Casey adrian.casey at internode.on.net
Mon Nov 13 06:03:11 EST 2006


I have a multi-threaded python application which uses pexpect to connect to
multiple systems concurrently.  Each thread within my application is a
connection to a remote system.  The problem is when one of the child
threads runs a command which generates an unlimited amount of output.  The
classic example of this is the "yes" command.  If you
execute "pexpect.run('yes')", your cpu will sit at 100% forever.

Here is a simple multi-threaded program using pexpect which demonstrates the
problem.  The command 'yes' is run in a thread.  The parent says that when
the alarm goes off, run the handler function.  The thread sets the alarm to
trigger after 5 seconds.

#!/usr/bin/env python
import signal, os, pexpect, threading

def handler(signum, frame):
# This should get called after 5 seconds when the alarm fires.
        os.system('killall yes')
        print "The yes command has been killed!"

def runyes():
# Run the 'yes' command in a thread.  Set an alarm
# to fire in 5 seconds.
        signal.alarm(5)
        print "Running yes command..."
# If you run 'sleep 10' instead, this works.
        pexpect.run('yes')
# Re-set the alarm.  (This is never reached.  The 'yes'
# command runs forever and is not interrupted by the alarm)
        signal.alarm(0)

signal.signal(signal.SIGALRM, handler)
t = threading.Thread(target=runyes)
t.start()
t.join()
# END of code

Note that if the 'yes' command is substituted for 'sleep 10', the code works
perfectly.

Why can't the 'yes' command be interrupted using the SIGALRM method when the
sleep command can?  I realize that noone would really run 'yes' but what if
a user account has a buggy .bashrc and loops forever?  Just one thread
locking up like this holds up all the others.

Any ideas or suggestions on how to handle such situations in a
multi-threaded way would be appreciated.

Cheers.
Adrian Casey.
Alice Springs Linux User Goup.
http://www.aslug.org.au



More information about the Python-list mailing list