SimpleDaemon

Da Php-faq.org.

[modifica] Come posso creare un semplice demone in PHP?

La definizione di un demone richiede il soddisfacimento di diversi criteri che comunque non vengono sempre rispettati (specialmente da questa implementazione).

Il codice è breve e di facile comprensione (per chi ha familiarità con i demoni negli ambienti unix-like) tuttavia può e deve essere migliorata per essere utilizzata in produzione.

#! /usr/bin/env php
<?php

error_reporting(E_ALL|E_STRICT);

function daemonize ($user, $root, $umask)
{
    /* First fork off and die */
    if (($pid = pcntl_fork()) < 0) {
        echo "[FATAL] Can't complete the grandparent fork off and die.\n";
        exit(1);
    } else if ($pid != 0) {
        /* Granparent committing suicide */
        exit(0);
    }

    /* Waiting 1 second for the grandparent funeral */
    sleep(1);

    /* Making the daemon the leader of its own group */
    posix_setsid();

    /* Second fork off and die */
    if (($pid = pcntl_fork()) < 0) {
        echo "[FATAL] Can't complete the parent fork off and die.\n";
        exit(1);
    } else if ($pid != 0) {
        /* Parent committing suicide */
        exit(0);
    }

    /* Waiting 1 second for the parent funeral */
    sleep(1);

    /* Checking whether the parent of daemon is init or not */
    if (posix_getppid() != 1) {
        echo "[WARNING] Init is not the parent of the daemon.\n";
    }

    /* Changing the daemon root directory */
    chroot($root);

    /* Setting the requested umask */
    umask($umask);

    /* Acquiring the privileges of the given user */
    $privileges = posix_getpwnam($user);
    posix_setuid($privileges['uid']);
    posix_setgid($privileges['gid']);

    /* A PHP daemon-like process has been created successfully */
    return 0;
}

daemonize('nobody', '/', 0);

while (true) {
    // do something
    sleep(10);
}

?>

Questo codice quando richiamato da shell crea un piccolo demone che non fa altro che aspettare all'infinito scandendo il tempo 10 secondi alla volta, ma essendo codice didattico/dimostrativo si presta bene alla comprensione delle tecniche utilizzate per creare demoni anche complessi in PHP.

Da notare è anche il fatto che alcune funzioni richieste per eseguire correttamente questo script devono essere esplicitamente abilitate durante la compilazione di PHP stesso, che dovrà essere anche eseguito in modalità CLI o CGI etc come utente `root`.

Strumenti personali