Using signal.alarm to terminate a thread
adrian.casey at internode.on.net
Tue Nov 14 10:30:16 CET 2006
Nick Craig-Wood wrote:
> Adrian Casey <adrian.casey at internode.on.net> wrote:
>> I have a multi-threaded python application which uses pexpect to connect
>> 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.
>> 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
>> problem. The command 'yes' is run in a thread. The parent says that
>> 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..."
> pexpect.run('yes', timeout=5)
> t = threading.Thread(target=runyes)
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