how to do a debian daemon with php script

Posted on 2009-02-18
Last Modified: 2012-05-06
hi all,

i want to make a debian init.d daemon which runs a php script in shell but i want this to run infinitely without exploiting all the system resources. it basically checks a mysql db and with conditions make files in a temp directory.

first i made a cronjob which runs every minute but it's not enough for me because it must continously check db and if the conditions met it must create temp files in real-time.

in the below link i could make daemon sh script which runs my php file, but if i put my script in a do loop block cpu is getting %50 load.

hope i could explain my problem.
Question by:yasincelik
    LVL 2

    Accepted Solution

    Hi, yo can try a PEAR class called: System_Daemon. And so now you can just:

    require_once "System/Daemon.php";                 // Include the Class
    System_Daemon::setOption("appName", "mydaemon");  // Minimum configuration
    System_Daemon::start();                           // Spawn Deamon!

    // CODE ----


    And that's all there is to it. The code after that, will run in your server's background. So next, if you create a while(true) loop around that code, the code will run indefinitely. Remember to build in a sleep(5) to ease up on system resources.

    You could download the package from PEAR, or, if you have PEAR installed on your system: just run this from a console:  
    pear install -f System_Daemon

    You can also update it using that last command.

    #!/usr/bin/php -q
     * System_Daemon turns PHP-CLI scripts into daemons.
     * PHP version 5
     * @category  System
     * @package   System_Daemon
     * @license
     * @version   SVN: Release: $Id: logparser.php 174 2009-02-12 12:13:47Z kevin $
     * @link
     * System_Daemon Example Code
     * If you run this code successfully, a daemon will be spawned
     * but unless have already generated the init.d script, you have
     * no real way of killing it yet.
     * In this case wait 3 runs, which is the maximum for this example. 
     * In panic situations, you can always kill you daemon by typing
     * killall -9 logparser.php
     * OR:
     * killall -9 php
    // Allowed arguments & their defaults 
    $runmode = array(
        "no-daemon" => false, 
        "help" => false,
        "write-initd" => false
    // Scan command line attributes for allowed arguments
    foreach ($argv as $k=>$arg) {
        if (substr($arg, 0, 2) == "--" && isset($runmode[substr($arg, 2)])) {
            $runmode[substr($arg, 2)] = true;
    // Help mode. Shows allowed argumentents and quit directly
    if ($runmode["help"] == true) {
        echo "Usage: ".$argv[0]." [runmode]\n";
        echo "Available runmodes:\n"; 
        foreach ($runmode as $runmod=>$val) {
            echo " --".$runmod."\n";
    // Make it possible to test in source directory
    // This is for PEAR developers only
    ini_set('include_path', ini_get('include_path').':..');
    // Include Class
    require_once "System/Daemon.php";
    // Setup
    $options = array(
        "appName" => "logparser",
        "appDir" => dirname(__FILE__),
        "appDescription" => "Parses vsftpd logfiles and stores them in MySQL",
        "authorName" => "Kevin van Zonneveld",
        "authorEmail" => "",
        "sysMaxExecutionTime" => "0",
        "sysMaxInputTime" => "0",
        "sysMemoryLimit" => "1024M",
        "appRunAsGID" => 1000,
        "appRunAsUID" => 1000
    // Overrule the signal handler with any function
    System_Daemon::setSigHandler(SIGCONT, array("System_Daemon",
    // This program can also be run in the forground with runmode --no-daemon
    if (!$runmode["no-daemon"]) {
        // Spawn Daemon 
    // With the runmode --write-initd, this program can automatically write a 
    // system startup file called: 'init.d'
    // This will make sure your daemon will be started on reboot 
    if (!$runmode["write-initd"]) {
        System_Daemon::log(System_Daemon::LOG_INFO, "not writing ".
            "an init.d script this time");
    } else {
        if (($initd_location = System_Daemon::writeAutoRun()) === false) {
            System_Daemon::log(System_Daemon::LOG_NOTICE, "unable to write ".
                "init.d script");
        } else {
            System_Daemon::log(System_Daemon::LOG_INFO, "sucessfully written ".
                "startup script: ".$initd_location);
    // Run your code
    // Here comes your own actual code
    // This variable gives your own code the ability to breakdown the daemon:
    $runningOkay = true;
    // This variable keeps track of how many 'runs' or 'loops' your daemon has
    // done so far. For example purposes, we're quitting on 3.
    $cnt = 1;
    // While checks on 3 things in this case:
    // - That the Daemon Class hasn't reported it's dying
    // - That your own code has been running Okay
    // - That we're not executing more than 3 runs 
    while (!System_Daemon::isDying() && $runningOkay && $cnt <=3) {
        // What mode are we in?
        $mode = "'".(System_Daemon::isInBackground() ? "" : "non-" ).
            "daemon' mode";
        // Log something using the Daemon class's logging facility
        // Depending on runmode it will either end up:
        //  - In the /var/log/logparser.log
        //  - On screen (in case we're not a daemon yet)  
            " running in ".$mode." ".$cnt."/3");
        // In the actuall logparser program, You could replace 'true'
        // With e.g. a  parseLog('vsftpd') function, and have it return
        // either true on success, or false on failure.
        $runningOkay = true;
        //$runningOkay = parseLog('vsftpd');
        // Should your parseLog('vsftpd') return false, then
        // the daemon is automatically shut down.
        // An extra log entry would be nice, we're using level 3,
        // which is critical.
        // Level 4 would be fatal and shuts down the daemon immediately,
        // which in this case is handled by the while condition.
        if (!$runningOkay) {
            System_Daemon::log(System_Daemon::LOG_CRITICAL, "parseLog() ".
                "produced an error, ".
                "so this will be my last run");
        // Relax the system by sleeping for a little bit
    // Shut down the daemon nicely
    // This is ignored if the class is actually running in the foreground

    Open in new window


    Author Comment

    thanks for the solution. i will use this method which i was exactly looking for.

    and i found in google this article which explains system_daemon very good.

    Featured Post

    What Security Threats Are You Missing?

    Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

    Join & Write a Comment

    Suggested Solutions

    Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit ( and similar technologies have enjoyed wide adoption, making it possib…
    These days socially coordinated efforts have turned into a critical requirement for enterprises.
    Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
    The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

    745 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    16 Experts available now in Live!

    Get 1:1 Help Now