Andy's Blog » php daemon, php deamon, php deamon stop, dream4i1, ZFSZ, importance67w, 1SSM » PHP Daemon

PHP Daemon

PEAR有一个System_Daemon

作者网站上的说明: http://kevin.vanzonneveld.net/techblog/article/create_daemons_in_php/

类似这样安装:

aptitude -y update
aptitude -y install php-pear
pear install -f system_daemon

像这样使用:

require_once "System/Daemon.php";
// Bare minimum setup
System_Daemon::setOption("appName", "simple");
System_Daemon::setOption("authorEmail", "[email protected]");
 
// Spawn Deamon!
System_Daemon::start();
 
// Your PHP Here!
while (true) {
    
doTask();
}
 
// Stop daemon!
System_Daemon::stop();

综合实例

#!/usr/bin/php -q
<?php
/**
 * System_Daemon turns PHP-CLI scripts into daemons.
 *
 * PHP version 5
 *
 *
@category System
 *
@package   System_Daemon
 *
@author    Kevin <[email protected]>
 *
@copyright 2008 Kevin van Zonneveld
 *
@license   http://www.opensource.org/licenses/bsd-license.php
 *
@version   SVN: Release: $Id: logparser.php 215 2009-04-25 10:10:18Z kevin $
 *
@link      http://trac.plutonia.nl/projects/system_daemon
 */

 
/**
 * System_Daemon Example Code
 *
 * If you run this code successfully, a daemon will be spawned
 * but unless have already generated the init.d script, you have
 * no real way of killing it yet.
 *
 * In this case wait 3 runs, which is the maximum for this example.
 *
 *
 * In panic situations, you can always kill you daemon by typing
 *
 * killall -9 logparser.php
 * OR:
 * killall -9 php
 *
 */

 
// Allowed arguments & their defaults
$runmode = array(
    
"no-daemon" => false,
    
"help" => false,
    
"write-initd" => false
);
 
// Scan command line attributes for allowed arguments
foreach ($argv as $k=>$arg) {
    
if (substr($arg, 0, 2) == "--" && isset($runmode[substr($arg, 2)])) {
        
$runmode[substr($arg, 2)] = true;
    
}
}
 
// Help mode. Shows allowed argumentents and quit directly
if ($runmode["help"] == true) {
    
echo "Usage: ".$argv[0]." [runmode]\n";
    
echo "Available runmodes:\n";
    
foreach ($runmode as $runmod=>$val) {
        
echo " --".$runmod."\n";
    
}
    
die();
}
 
// 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";
 
// Setup
$options = array(
    
"appName" => "logparser",
    
"appDir" => dirname(__FILE__),
    
"appDescription" => "Parses vsftpd logfiles and stores them in MySQL",
    
"authorName" => "Kevin van Zonneveld",
    
"authorEmail" => "[email protected]",
    
"sysMaxExecutionTime" => "0",
    
"sysMaxInputTime" => "0",
    
"sysMemoryLimit" => "1024M",
    
"appRunAsGID" => 1000,
    
"appRunAsUID" => 1000
);
 
System_Daemon::setOptions($options);
 
// Overrule the signal handler with any function
System_Daemon::setSigHandler(SIGCONT, array("System_Daemon",
    
"defaultSigHandler"));
 
 
// This program can also be run in the forground with runmode --no-daemon
if (!$runmode["no-daemon"]) {
    
// Spawn Daemon
    
System_Daemon::start();
}
 
// With the runmode --write-initd, this program can automatically write a
// system startup file called: 'init.d'
// This will make sure your daemon will be started on reboot
if (!$runmode["write-initd"]) {
    
System_Daemon::log(System_Daemon::LOG_INFO, "not writing ".
        
"an init.d script this time");
} else {
    
if (($initd_location = System_Daemon::writeAutoRun()) === false) {
        
System_Daemon::log(System_Daemon::LOG_NOTICE, "unable to write ".
            
"init.d script");
    
} else {
        
System_Daemon::log(System_Daemon::LOG_INFO, "sucessfully written ".
            
"startup script: ".$initd_location);
    
}
}
 
// Run your code
// Here comes your own actual code
 
// This variable gives your own code the ability to breakdown the daemon:
$runningOkay = true;
 
// This variable keeps track of how many 'runs' or 'loops' your daemon has
// done so far. For example purposes, we're quitting on 3.
$cnt = 1;
 
// While checks on 3 things in this case:
// - That the Daemon Class hasn't reported it's dying
// - That your own code has been running Okay
// - That we're not executing more than 3 runs
while (!System_Daemon::isDying() && $runningOkay && $cnt <=3) {
    
// What mode are we in?
    
$mode = "'".(System_Daemon::isInBackground() ? "" : "non-" ).
        
"daemon' mode";
    
    
// Log something using the Daemon class's logging facility
    
// Depending on runmode it will either end up:
    
//  - In the /var/log/logparser.log
    
//  - On screen (in case we're not a daemon yet) 
    
System_Daemon::log(System_Daemon::LOG_INFO,
        
System_Daemon::getOption("appName").
        
" running in ".$mode." ".$cnt."/3");
    
    
// In the actuall logparser program, You could replace 'true'
    
// With e.g. a  parseLog('vsftpd') function, and have it return
    
// either true on success, or false on failure.
    
$runningOkay = true;
    
//$runningOkay = parseLog('vsftpd');
    
    
// Should your parseLog('vsftpd') return false, then
    
// the daemon is automatically shut down.
    
// An extra log entry would be nice, we're using level 3,
    
// which is critical.
    
// Level 4 would be fatal and shuts down the daemon immediately,
    
// which in this case is handled by the while condition.
    
if (!$runningOkay) {
        
System_Daemon::log(System_Daemon::LOG_ERR, "parseLog() ".
            
"produced an error, ".
            
"so this will be my last run");
    
}
    
    
// Relax the system by sleeping for a little bit
    
// iterate also clears statcache
    
System_Daemon::iterate(2);
 
    
$cnt++;
}
 
// Shut down the daemon nicely
// This is ignored if the class is actually running in the foreground
System_Daemon::stop();
?>

控制 Daemon

执行daemon

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

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

tail /var/log/logparser.log

看看是不是还在运行:

ps uf -C logparser.php

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

killall -9 logparser.php

开始 / 停止 (只支持Debian & Ubuntu)
真正的daemons有一个init.d文件. 记得怎么样启动apache吧?

/etc/init.d/apache2 restart

用这个方法停止更好:

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

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

$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!

启动时运行daemon
Debian & Ubuntu 上输入以下命令:

update-rc.d logparser defaults

现在系统启动就会自动运行logparser.

如果要停止, 输入如下命令:

update-rc.d -f logparser remove

另外, PHP的进程控制, 可以看
http://www.php.net/manual/en/book.pcntl.php

Incoming search terms:

Tags: PHP, pear, cron, Daemon, 定时

本文地址: http://www.21andy.com/new/20090608/1320.html