PHP Programming/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.

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.