Running a PHP Script as Daemon

For our ongoing project at Leevio, I had to find a way to run a php script as a daemon. I checked out a few techniques. I didn’t like any of them much. I needed a way to run the intended script and then exit the terminal leaving the script to keep running in the background.

After a bit of hard work, I chose to use the PCNTL functions to achieve my goal. Here’s the code I used:

 
<?php
declare(ticks=1);
 
$pid = pcntl_fork();
if ($pid == -1) {
    die("could not fork");
} else if ($pid) {
        exit(); // it's the parent -- lets quit
    } else {
    // it's the child -- nothing to do at the moment
    }
 
// detatch from the terminal
if (posix_setsid() == -1) {
    die("could not detach from terminal");
}
 
// setup signal handlers
pcntl_signal(SIGTERM, "sig_handler");
pcntl_signal(SIGHUP, "sig_handler");
 
// launch the script -- transfer the args to the child script
shell_exec("php script.php {$argv[1]} {$argv[2]} {$argv[3]} ");
 
function sig_handler($signo) {
 
    switch ($signo) {
        case SIGTERM:
        // handle shutdown tasks
            exit;
            break;
        case SIGHUP:
        // handle restart tasks
            break;
        default:
    // handle all other signals
    }
 
}
 
?>

Note that, in this case, the daemon quits the moment the shell_exec() command is executed. We are executing our intended PHP script as a sub process which has been detached from the terminal. The script has a while loop to keep it running forever. So, we can safely quit the main process while the forked process remains alive with the php script being executed :D

This entry was posted in Blog Post and tagged . Bookmark the permalink.

6 Responses to Running a PHP Script as Daemon

  1. hasin says:

    M, definitely a very good work. I knew about System_Daemon but this one looks really cool. Do you know if there is any OS specific issue with pcntl_fork or it is cross OS (forget abt windows – I am talking about different flavors of linux and mac os)

    Keep up the good work. :)

  2. Pingback: ???????: ???????? ?? « ???????, ??????

  3. Mardix says:

    I kinda like it too, but what about “nohup” in the shell. IMHO, “nohup” should keep the script running even if you exit the shell.

    nohup php script.php {args} &

  4. InvarBrass says:

    I had implemented a very crude daemon in PHP a while ago. The code can be found here: http://forum.projanmo.com/topic11447.html

    (That code was basically translated from a simple daemon I’d written in FreePascal a long time ago – hence the code looks so un-PHP-ish and ugly ;) ).

    WRT Mr. Hasin’s comment above, I think you should implement the double-fork technique to ensure the code works reliably on all unices. I’m not familiar with darwin though, but IIRC solaris (and perhaps freebsd too) requires the double-fork. Your code (single-fork) will work fine in linux, but will fail in other unices. Please refer to the forum post for the code.

  5. anon says:

    sonic server daemon maybe?

    http://dev.pedemont.com/sonic

  6. Pingback: Understanding the Role of Daemons in PHP

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">