PHP Programming/CLI/Daemonization

From Wikibooks, open books for an open world
Jump to: navigation, search

Back to PHP

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[edit]

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[edit]

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.

Nanoserv Sonic Server Daemon