开发者

Can I make a section of code time out?

I'm working with a class that ma开发者_开发百科kes a remote connection to a server. A problem that I'm running into is if the connection doesn't get a response, it'll wait until it does.

This class does not have a timeout built into it, and I don't want to modify it if I can avoid it.

Is there any way that I can wrap a section of code in something like this?

try(timeout seconds){
}catch(){
    //exception handle
}timeout(){
    // timeout handline
}

EDIT: I use the remote connection as one problem. I have others that I need to solve with this as well, like making system calls with exec or other similar things.


Not for only a section of the code.

There is however alternative solutions, without modifying the original code, as requested:

set_time_limit

set_time_limit() will abort the whole script if it runs for too many time. You could still setup a shutdown function.

pcntl_alarm

pcntl_alarm() will send you a signal after a given amount of time, which may abort the blocking syscall the class is doing at that time, and this may allow you to ask the class to abort its operations if it provides such method. This may not be suitable in a web server environment, though.

Default timeouts

If the class is using stream functions, you may be able to set a default timeout:

ini_set('default_socket_timeout', 5);
stream_context_set_default(array(
    'http' => array(
        'timeout' => 5, 
    ),
));

Execute in a separate process

You could fork with pcntl_fork(), but this is not suitable in a server environment.

You could also use proc_open or popen to execute a PHP script in a separate process and kill it if it runs for a too long time. (After the process is spawned, do an idle wait on the process' stdout stream with stream_select.)

Or setup a server for handling these tasks.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜