OK...I've been killing myself trying to get this to work properly and it just won't. So I'm hoping someone on this board with more experience with sockets and/or forked processes can help me out a bit.
I've got a 'server' process written in php that starts and waits for connections. As connections come in it forks to handle them.
This works fine.
However, when someone disconnects, the PID for the forked process will not die. It just becomes DEFUNCT. I'm using pcntl_waitpid() and it still isn't working correctly.
If someone can point me in a proper direction I would REALLY appreciate it.
Here's the code:
#!/usr/local/bin/php -q
<?php
error_reporting (E_ALL);
/* Allow the script to hang around waiting for connections. */
set_time_limit (0);
/* Turn on implicit output flushing so we see what we're getting
* as it comes in. */
ob_implicit_flush ();
$address = 'xx.xx.xx.xx'; /* taken out for posting purposes */
$port = XXXX; /* TAKEN OUT FOR POSTING PURPOSES */
$sock = socket_create (AF_INET, SOCK_STREAM, 0);
$ret = socket_bind ($sock, $address, $port);
$ret = socket_listen ($sock, 5);
function sig_handler()
{
/* THIS IS SET TO SPIT OUT OUTPUT IN ORDER TO DEBUG IT */
$pid = pcntl_waitpid(-1, $status, WNOHANG);
if($pid > 0)
{
print("PID $pid exited.\n");
}
else
{
die("PID $pid DID NOT EXIT!!!!!!!!\n");
}
return;
}
pcntl_signal(SIGCHLD, "sig_handler");
while (true)
{
if($connfd = socket_accept($sock))
{
if(($child_pid = pcntl_fork()) == 0)
{
socket_close($sock);
$welcome_msg = "200 - connection ready\n";
socket_write($connfd, $welcome_msg, strlen($welcome_msg));
while(true)
{
$buf = socket_read($connfd, 2048);
$buf = trim($buf);
if($buf == "exit")
{
/* GET THE PID FOR THIS CHILD PROCESS */
$pid = posix_getpid();
$bye_msg = "Bye!\n\n";
socket_write($connfd, $bye_msg, strlen($bye_msg));
print("killing pid: $pid....\n"); /* DEBUG */
posix_kill($pid, SIGCHLD); /* THIS USES THE PCNTL_WAITPID() IN 'sig_handler' */
break 2;
}
else
{
$sendto = "YOU TYPED: '$buf'\n";
socket_write($connfd, $sendto, strlen($sendto));
}
}
}
socket_close($connfd);
}
}
?>
Everyting works, EXCEPT killing off the forked process...
Right now all it is doing is echo'ing back whatever is typed in. To test this I'm just telnetting to the port to connect. Typing 'exit' disconnects.
I took out a lot of debug code to make it more concise for posting...but the big problem is with getting rid of the forked process...
Any help would be GREATLY appreciated.
Thanks.
-- Jason