Jump to content

Timeout a while loop


agravayne

Recommended Posts

Hello All,

 

I have a while loop that reads data from a socket until it reaches a specified teminator. This works but I need to be able to time this out so that if  the terminator is for some reason omitted then the while loop won't wait forever. I have tried adding a incremental counter but this only ever gets up to one - whether it reads or not.

 

Here is my code.

 

while(substr($clients[$i]['Data'], strlen($clients[$i]['Data'])-4, 4)!="TS:\n")
{
   if(false!== ($data = socket_recv($tempsock, $buf,10240,0)));
   {$clients[$i]['Data'].=$buf;}
}

 

Any ideas

Thanks

 

Link to comment
https://forums.phpfreaks.com/topic/180401-timeout-a-while-loop/
Share on other sites

Try like this:

 

$startTime = time();
$timeout = 60;   //timeout in seconds

while(substr($clients[$i]['Data'], strlen($clients[$i]['Data'])-4, 4)!="TS:\n")
{
   if(time() > $startTime + $timeout) {
     break;
   }

   if(false!== ($data = socket_recv($tempsock, $buf,10240,0)));
   {$clients[$i]['Data'].=$buf;}
   
}

Link to comment
https://forums.phpfreaks.com/topic/180401-timeout-a-while-loop/#findComment-951703
Share on other sites

@Mchl... but if the while loop only gets to the first execution and then hangs that won't have any effect...

 

@agravayne...have you've looked at set_time_limit()?

http://php.net/manual/en/function.set-time-limit.php

 

in saying that, it wouldn't end the script gracefully...

 

 

Link to comment
https://forums.phpfreaks.com/topic/180401-timeout-a-while-loop/#findComment-951719
Share on other sites

Note: The set_time_limit() function and the configuration directive max_execution_time  only affect the execution time of the script itself. Any time spent on activity that happens outside the execution of the script such as system calls using system()' date=' stream operations, database queries, etc. is not included when determining the maximum time that the script has been running. This is not true on Windows where the measured time is real. [/quote']

 

I wonder if socket_recv does count towards this limit. ???

 

[edit]

 

Maybe you should try setting MSG_DONTWAIT flag?

Link to comment
https://forums.phpfreaks.com/topic/180401-timeout-a-while-loop/#findComment-951745
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.