0

我想在 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);
    }

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

4

3 回答 3

0

看看: http: //pear.php.net/package/System_Daemon

于 2012-04-26T16:15:05.603 回答
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
        }
    }
于 2012-05-03T06:27:20.463 回答
0

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

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

于 2013-04-17T14:43:33.067 回答