Jump to content

sockets / signals


RoyHB

Recommended Posts

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
Share on other sites

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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.