Daemonization

A daemon is an application that runs in the background, as opposed to being directly operated by the user. Examples of daemons are Cron and MySQL.

Daemonizing a process with PHP is very easy, and requires PHP 4.1 or higher compiled with --enable-pcntl.

Building a Daemon

We'll start with set_time_limit(0) to let our script run indefinitely. Next, we fork the PHP process with pcntl_fork. Finally, we use posix_setsid to tell the child process to run in the background as a session leader.

<?
   set_time_limit(0);   // Remove time limit 
 
   if (pcntl_fork) {  // Fork process
     print "Daemon running.";
   } else {
     $sid = posix_setsid; // Make child process session leader
       
     if ($sid < 0)
            exit;
 
     while (true) {
                        // Daemon script goes here
     }
   }
?>

The code inside the while statement will run in the background until exit or die is explicitly called.

Applications

While daemonizing a script can be useful, it is not appropiate for every script. If a script only needs to be executed at a certain time, it can take advantage of Cron for scheduled execution.

See also



  This article uses material from the Wikipedia page available here. It is released under the Creative Commons Attribution-Share-Alike License 3.0.

PHP_Programming/Daemonization
 



 

Connect with defaultLogic
What We've Done
Led Digital Marketing Efforts of Top 500 e-Retailers.
Worked with Top Brands at Leading Agencies.
Successfully Managed Over $50 million in Digital Ad Spend.
Developed Strategies and Processes that Enabled Brands to Grow During an Economic Downturn.
Taught Advanced Internet Marketing Strategies at the graduate level.


Manage research, learning and skills at defaultLogic. Create an account using LinkedIn or facebook to manage and organize your Digital Marketing and Technology knowledge. defaultLogic works like a shopping cart for information -- helping you to save, discuss and share.

Visit defaultLogic's partner sites below:
PopFlock.com : Music Genres | Musicians | Musical Instruments | Music Industry
NCR Works : Retail Banking | Restaurant Industry | Retail Industry | Hospitality Industry

  Contact Us