守护PHP脚本

时间:2012-04-26 16:10:14

标签: php

我想在Linux下的PHP 5.3下守护一个php脚本(Jobque.php)

这个想法是这样调用脚本:

php -f ./application/Model/Jobque.php start

并且脚本会执行shell_exec将自己置于后台并按此处理

nohup php -f /var/.../application/Model/Jobque.php process 2> /dev/null & echo $!

这最后一个命令确实在后台启动了脚本并且一切正常,但是当我从脚本本身发出此命令时,脚本会一直等到执行停止(从不)

这是我用来启动脚本作为守护进程的函数--Windows部分工作

public function start_daemon() {
        if (file_exists ( $this->pidfile ))
            die ( 'process is already running - process pidfile already exists -> ' . $this->pidfile );
        $cmd = 'php -f ' . __FILE__ . ' process';
        if (substr ( php_uname (), 0, 7 ) == "Windows") {
            $WshShell = new COM ( "WScript.Shell" );
            $oExec = $WshShell->Run ( "$cmd /C dir /S %windir%", 0, false );
            exec ( 'TASKLIST /NH /FO "CSV" /FI "imagename eq php.exe" /FI "cputime eq 00:00:00"', $output );
            $output = explode ( '","', $output [0] );
            $pid = $output [1];
            file_put_contents ( $this->pidfile, $pid );
        } else {
            $execstr = "nohup $cmd 2> /dev/null & echo $!";
            //echo $execstr; -- the execstr is right in itself
            $PID = shell_exec ( $execstr );
            //echo $PID; -- we never get here
            file_put_contents ( $this->pidfile, $PID );
        }
        echo ('JobQue daemon started with pidfile:' . $this->pidfile);
    }

我在这里做错了什么,怎么做对了?

3 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

我最终使用pcntl_fork在Linux下守护脚本,如下所示:

public function start_daemon($worker) {
        if (file_exists ( $this->get_pidfile ( $worker ) ))
            die ( 'process is already running - process pidfile already exists -> ' . $this->get_pidfile ( $worker ) . "\n" );
        $cmd = 'php -f ' . __FILE__ . ' process';
        if ($this->is_win) {
            $WshShell = new COM ( "WScript.Shell" );
            $oExec = $WshShell->Run ( "$cmd /C dir /S %windir%", 0, false );
            exec ( 'TASKLIST /NH /FO "CSV" /FI "imagename eq php.exe" /FI "cputime eq 00:00:00"', $output );
            $output = explode ( '","', $output [0] );
            $pid = $output [1];
            file_put_contents ( $this->get_pidfile ( $worker ), $pid );
            echo ('JobQue daemon started with pidfile:' . $this->get_pidfile ( $worker ) . "\n");
        } else {
            $PID = pcntl_fork ();
            if ($PID) {
                file_put_contents ( $this->get_pidfile ( $worker ), $PID );
                echo ('JobQue daemon started with pidfile:' . $this->get_pidfile ( $worker ) . "\n");
                exit (); // kill parent
            }
            posix_setsid (); // become session leader
            chdir ( "/" );
            umask ( 0 ); // clear umask
            $this->process_jobs (); //start infinite loop
        }
    }

答案 2 :(得分:0)

查看daemonize命令:http://software.clapper.org/daemonize/index.html

或者,ubuntu上的“upstart”:http://upstart.ubuntu.com/