Page 1 of 1

Socket dilemma

Posted: Tue Jun 08, 2010 9:30 am
by anomie
Hi,

I'm new to php socket programming and although I've trawled Google considerably, I can't seem to find a clear answer to the following problem. Please could you help?

I have a daemon whose inner loop simply reads in data from a socket and processes it.

Code: Select all

while (  !feof ( $sock ) )
	{
		$line = fgets ( $sock, 1024 );	
                echo $line;
                sleep (0.1);
	}
I want the control to exit the loop when it gets an EOF, but I also want to capture signals with a signal handler, so that if someone sends a SIGINT for example, the daemon will respond to the signal and control will pass into the signal handler.

Sometimes there will be many minutes between one line of the stream and the next. Therefore it is not suitable to use a blocking socket because if it's sent a SIGINT it may not respond to that signal for many minutes as it is waiting for a line of data.

However if I use a non-blocking socket, it uses 100% cpu, even if I put a sleep (0.1) into the loop.

I have a feeling that select() or socket_select() could help me here but all the documentation I can find seems to suggest that select() is only useful when you have multiple sockets and that it would not give me the non-blocking type of behaviour I require.
Thanks in advance!
A

Re: Socket dilemma

Posted: Tue Jun 08, 2010 10:53 am
by Weirdan
anomie wrote:However if I use a non-blocking socket, it uses 100% cpu, even if I put a sleep (0.1) into the loop.
The problem is that sleep() accepts integer argument, so when you pass float 0.1 it gets rounded to 0 and you get no sleep at all. Use usleep() if you need to sleep for a fraction of second.

Re: Socket dilemma

Posted: Tue Jun 08, 2010 11:59 am
by anomie
Weirdan, you are a star! I'm using usleep ( 1000 ) now and the CPU has gone down to below 1% even though checking the socket every 1ms is far more than I need. Thanks, I really appreciate your reply.