Using signal.alarm to terminate a thread

Adrian Casey adrian.casey at
Tue Nov 14 10:30:16 CET 2006

Nick Craig-Wood wrote:

> Adrian Casey <adrian.casey at> wrote:
>>  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 "'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.
> 1) Don't ever mix threads and signals - you are heading for trouble!
> 2) pexpect has a timeout parameter exactly for this case
> import os, pexpect, threading
> def runyes():
>         print "Running yes command..."
>'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 'yes' command presents a class of
command which can not be easily be handled by pexpect.  As far as I know,
mixing threads and signals is OK provided the parent creates the alarm.


More information about the Python-list mailing list