Fork+Timeout

Donn Cave donn at u.washington.edu
Fri Mar 26 17:50:11 EST 2004


In article <c40uq1$f48$1 at news.web.de>, "Oliver Kurz" <olku at web.de> 
wrote:

> do someone new how I can do the following?
> 
> I call a method which reads from a socket. So ... this method could hang
> forever and so my call hangs too ...
> 
> So ... I can not change the behavior of this Method, so I have to change my
> call.
> 
> I though by forking the call to this function and set a timeout to this
> call, so my program won't hang forever.
> 
> But I don't know how I should do this and if this is the correct/best way to
> do this.

You might be able to get something like that to work.  If you
want to give it a try, I would start by learning to use
signal.alarm(), and then see if its SIGALRM signal will
interrupts a socket recv() on your platform.  You won't need
fork, I don't think.

You can probably do better, though, if you can get at the
socket.  My favorite way to approach this kind of situation
is to wait for I/O on all relevant devices with select.select().
When select says your method's socket is readable, you can
call the method, and it will return right away.

You can probably do better, though.  I like select.select(),
which waits for I/O on any of a collection of devices.  That
will tell you when it's safe to call your method.

It will work only if 1) you have access to the socket object,
2) the method doesn't use fileobject I/O on the socket (because
its buffering confuses the issue), and 3) the other inputs to
your program work with select.  (Oh, and if you're on UNIX.)
If it's an X11 graphical application, you'll want to use the
external I/O dispatching mechanism provided by your X toolkit
instead.

   Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list