代码:
exec('ps aux |grep tweet',$output,$return_var);
if(count($output)>0){
exec('php ' . DOCROOT . 'gremlins/tweet_gremlin.php &');
file_put_contents(DOCROOT . 'gremlins/tweet_gremlin.log', date('r') . ' Tweet Gremlin was not running. Starting now...');
}
在我看来,这段代码是有道理的,但它只是导致浏览器无限循环。我想做的是检查tweet_gremlin.php是否正在运行,如果没有运行,请启动它。DOCROOT是代码中前面定义的常量。
我发现,有时在执行ps -aux | grep "something"
时,总会有一个过程。这个过程基本上就是你的命令本身!因此,在php中使用命令之前,请先在shell中实际试用这些命令。
您可以使用:
if (!exec("ps aux | grep tweet | grep -v grep")) {
// do something
}
grep -v
部分从列表中删除grep
进程。
此外,要使用exec
等执行后台进程,您需要重定向输出,否则您的脚本将挂起,直到进程完成。例如:
exec('php script.php >/dev/null &');
我认为您可能需要尝试
if( count($output)==0 )
因为你想测试流程是否不存在,对吗?
你或其他人可能会发现这很有用,这是我很久以前写的脚本
<?php
// shut system if wget is not running
function rempty($tbl)
{
foreach ($tbl as $key => $val)
{
if (trim($val) == '')
unset ($tbl[$key]);
}
return $tbl;
}
while (count(rempty(explode("'n",trim(shell_exec('pgrep wget'))))) > 0)
sleep(1);
echo 'done. shutting down in 30 mins...';
sleep (30*60);
shell_exec('sudo halt');
?>