MSSql MySql Python javascript PHP java DotNet Ruby Hackme Takeawy Code Twitter Facebook

The house of developers, A website to classify and rank developers

 
 
 
 
Country Rank: 19
World Rank: 129
Profile Viewed: 1040
Points: 4140
06 Mar 2011

Running php script as Daemon ...

You can run your code in a for loop, but some times you need to run a PHP script a daemon.

The most advantage of this is to running the process in the background, also if an error occurred the script will be automatically restarted.

 

Below is a PHP code , that can run another PHP script a a daemon.

 

#!/usr/bin/php

 

 

/**

* Handling SIG handlers

*/

$sigterm = false;

$sighup = false;

 

/**

* SIG handler

*/

function sig_handler($signo) {

        global $sigterm, $sigup;

 

        if($signo == SIGTERM) {

                $sigterm = true;

        } else if($signo == SIGHUP) {

                $sighup = true;

        }

}

 

 

// Forking the php script

global $sigterm, $sighup;

 

// Setting the maximum execution time to zero for the script to make sure that it can run forever

ini_set("max_execution_time", "0");

 

//Setting the max input time to zero to make sure that it can give any required time to parse the input data (like, Post, Get, etc ..)

ini_set("max_input_time", "0");

 

//Set the number of seconds a script is allowed to run

set_time_limit(0);

 

pcntl_signal(SIGTERM, "sig_handler");

pcntl_signal(SIGHUP, "sig_handler");

 

 

// Forking the required process into a background child process

$pid = pcntl_fork();

 

if($pid == -1) {

        die("Error : Forking failed ... !");

}

 

if($pid) {

        // Printing the process id on the monitor so the user can kill it manually by kill -9 command

        echo($pid);

        return 0;

}

 

while(!$sigterm) {

 

        // Executing the required php script

        exec('php /path/to/your/script');

 

        // sleep time in secounds to prevent hundreds of executions pre second

       //(i.e if the script contain an error it will be finished in less  than a second and

       // the next one will start when this finish, and so on

        sleep(10);

}

 

//Exiting of zero

return 0;

Facebook Share Delicious Share Digg Share Google Buzz Share My Space Share Reddit Share Stumbleupon Share Technorati Share Twitter Share

Comments

Please, login or register to add a comment.