Socket dilemma

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
anomie
Forum Newbie
Posts: 2
Joined: Tue Jun 08, 2010 9:12 am

Socket dilemma

Post 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
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: Socket dilemma

Post 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.
anomie
Forum Newbie
Posts: 2
Joined: Tue Jun 08, 2010 9:12 am

Re: Socket dilemma

Post 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.
Post Reply