PEAR is archived and read-only

This mirror preserves historical PEAR package releases and metadata so existing references remain available.

Home » System » System_Daemon » Manual

Allows developers to create their own daemon applications on Linux systems using nothing but PHP.

Introduction to System_Daemon

Everyone knows PHP can be used to create websites. But it can also be used to create desktop applications and commandline tools. And now with a class called System_Daemon, you can even create daemons using nothing but PHP. And did I mention it was easy?

This how-to was ported from: http://kevin.vanzonneveld.net/techblog/article/create_daemons_in_php/. you can leave a comment there as well.

What is a Daemon?

A daemon is a Linux program that run in the background, just like a 'Service' on Windows. It can perform all sorts of tasks that do not require direct user input. Apache is a daemon, so is MySQL. All you ever hear from them is found in somewhere in /var/log, yet they silently power over 40% of the Internet. You reading this page, would not have been possible without them. So clearly: a daemon is a powerful thing, and can be bend to do a lot of different tasks.

Why PHP?

Most daemons are written in C. It's fast & robust. But if you are in a LAMP oriented company like me, and you need to create a lot of software in PHP anyway, it makes sense:

Possible use cases

What is a Daemon?

Some people use cronjobs for the same Possible use cases. Crontab is fine but it only allows you to run a PHP file every minute or so.

Cronjobs are a bit rude for this, they may spin out of control and don't provide a framework for logging, etc. Creating a daemon would offer more elegance & possibilities. Let's just say: there are very good reasons why a Linux OS isn't composed entirely of Cronjobs :)

How it works internally

Nerd alert!) When a daemon program is started, it fires up a second child process, detaches it, and then the parent process dies. This is called forking. Because the parent process dies, it will give the console back and it will look like nothing has happened. But wait: the child process is still running. Even if you close your terminal, the child continues to run in memory, until it either stops, crashes or is killed. In PHP: forking can be achieved by using the Process Control Extensions. Getting a good grip on it, may take some studying though.

System_Daemon

Because the Process Control Extensions' documentation is a bit rough, I decided to figure it out once, and then wrap my knowledge and the required code inside a PEAR class called: System_Daemon. And so now you can just:

System_Daemon Usage

<?php
    require_once "System/Daemon.php";                 // Include the Class

    System_Daemon::setOption("appName", "mydaemon");  // Minimum configuration
    System_Daemon::start();                           // Spawn Deamon!
?>

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.

Features & Characteristics Here's a grab of System_Daemon's features:

System_Daemon examples

To get the feeling how System_Daemon is used, try out the following examples.

System_Daemon examples

If you run this code successfully, a daemon will be spawned and stopped directly. You should find a log enty in /var/log/simple.log

#!/usr/bin/php -q
<?php
/**
 * System_Daemon turns PHP-CLI scripts into daemons.
 * 
 * PHP version 5
 *
 * @category  System
 * @package   System_Daemon
 * @author    Kevin <kevin@vanzonneveld.net>
 * @copyright 2008 Kevin van Zonneveld
 * @license   http://www.opensource.org/licenses/bsd-license.php New BSD Licence
 * @version   SVN: Release: $Id: simple.php 276201 2009-02-20 16:55:07Z kvz $
 * @link      http://trac.plutonia.nl/projects/system_daemon
 */

/**
 * System_Daemon Example Code
 * 
 * If you run this code successfully, a daemon will be spawned
 * and stopped directly. You should find a log enty in 
 * /var/log/simple.log
 * 
 */

// Make it possible to test in source directory
// This is for PEAR developers only
ini_set('include_path', ini_get('include_path').':..');

// Include Class
error_reporting(E_ALL);
require_once "System/Daemon.php";

// Bare minimum setup
System_Daemon::setOption("appName", "simple");
System_Daemon::setOption("authorEmail", "kevin@vanzonneveld.net");

//System_Daemon::setOption("appDir", dirname(__FILE__));
System_Daemon::log(System_Daemon::LOG_INFO, "Daemon not yet started so ".
    "this will be written on-screen");

// Spawn Deamon!
System_Daemon::start();
System_Daemon::log(System_Daemon::LOG_INFO, "Daemon: '".
    System_Daemon::getOption("appName").
    "' spawned! This will be written to ".
    System_Daemon::getOption("logLocation"));

// Your normal PHP code goes here. Only the code will run in the background
// so you can close your terminal session, and the application will
// still run.

System_Daemon::stop();
?>

Console action

Now that we've created an example daemon, it's time to fire it up! I'm going to assume the name of your daemon is logparser. This can be changed with the statement:

<?php
    System_Daemon::setOption("appName", "logparser")
?>

But the name of the daemon is very important because it is also used in filenames (like the logfile).

Execute Just make your daemon script executable, and then execute it:

    chmod a+x ./logparser.php
    ./logparser.php

Check Your daemon has no way of communicating through your console, so check for messages in:

    tail /var/log/logparser.log

And see if it's still running:

    ps uf -C logparser.php

Kill Without the start/stop files (see below for howto), you need to:

    killall -9 logparser.php

Autch.. Let's work on those start / stop files, right?

Start / Stop files (Debian & Ubuntu only) Real daemons have an init.d file. Remember you can restart Apache with the following statement?

    /etc/init.d/apache2 restart

That's a lot better than killing. So you should be able to control your own daemon like this as well:

    /etc/init.d/logparser stop
    /etc/init.d/logparser start

Well with System_Daemon you can write autostartup files using the writeAutoRun() method, look:

<?php
    $path = System_Daemon::writeAutoRun();
?>

On success, this will return the path to the autostartup file: /etc/init.d/logparser, and you're good to go!

Run on boot Surely you want your daemon to run at system boot.. So on Debian & Ubuntu you could type:

        update-rc.d logparser defaults

Done your daemon now starts every time your server boots. Cancel it with:

        update-rc.d -f logparser remove

Troubleshooting

Here are some issues you may encounter down the road.

I know I'm saying MySQL a lot, but you can obviously replace that with Oracle, MSSQL, PostgreSQL, etc.