RoyHB Posted November 15, 2011 Share Posted November 15, 2011 I have a PHP application that runs as a daemon. the daemon uses fsockopen to connect to an external server. When the daemon is terminated, for instance during a reboot, it looks like the connections to the remote server are persistent. The admin of the remote server tells me that he sees some of these connections for days after a daemon instance on my server has dies. My first thought was to use a linux/unix signal to tell the daemon to close the connections before it dies, but I haven't found a way to do that yet. The daemon seems to respond only to a sig-kill. In a perfect world I'd discover a way for the daemon to always run a function before it shuts down - within the function I'd close the open connections. I'd be very appreciative if someone could point me at either a way to cause a function to execute upon receipt of a sigkill or else a way to cause the daemon to recognise and act on some other less aggressive signal. Thanks Link to comment https://forums.phpfreaks.com/topic/251189-sockets-signals/ Share on other sites More sharing options...
RoyHB Posted November 16, 2011 Author Share Posted November 16, 2011 I discovered that it is necessary to call pcntl_signal_dispatch(); from within the main loop of my daemon in order to check whether any signals have been received - so the code skeleton that works looks like: Signal handler (Near the beginning of the program): pcntl_signal(SIGTERM, function ($signo) { global $handle; fclose($handle); exit(); }); Code to fork into a background task: $pid = pcntl_fork(); if($pid === -1) echo "error: unable to fork."; else if($pid) { exit(0); } posix_setsid(); sleep(1); ob_start(); Somewhere later: $handle = fsockopen(THE_ADDRESS_TO_COMMUNICATE_WITH, THE_PORT_TO_COMMUNICATE_WITH,$sockErrno,$sockErrStr); Then the main loop: while (TRUE) { pcntl_signal_dispatch(); .... my code that loops doing something that is (hopefully) useful } More info at: http://php.net/manual/en/function.pcntl-signal.php http://php.net/manual/en/function.pcntl-fork.php http://php.net/manual/en/function.pcntl-signal-dispatch.php Link to comment https://forums.phpfreaks.com/topic/251189-sockets-signals/#findComment-1288572 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.