2013-10-23 27 views
7

目前我的解决办法是:PHP:如何启动一个独立进程?

exec('php file.php >/dev/null 2>&1 &'); 

和file.php

if (posix_getpid() != posix_getsid(getmypid())) 
    posix_setsid(); 

有什么方法可以让我这样做只是以exec?

+0

我不这么认为。也许他posix_setsid示例可以帮助,但它使用fork()。 –

回答

5

不,这不能与exec()(也不shell_exec()system()


做。如果你已经安装了pcntl extension这将是:

function detached_exec($cmd) { 
    $pid = pcntl_fork(); 
    switch($pid) { 
     // fork errror 
     case -1 : return false 

     // this code runs in child process 
     case 0 : 
      // obtain a new process group 
      posix_setsid(); 
      // exec the command 
      exec($cmd); 
      break; 

     // return the child pid in father 
     default: 
      return $pid; 
    } 
} 

这样称呼它:

$pid = detached_exec($cmd); 
if($pid === FALSE) { 
    echo 'exec failed'; 
} 

// do some work 

// kill child 
posix_kill($pid, SIGINT); 
waitpid($pid, $status); 

echo 'Child exited with ' . $status; 
+0

我不想守护进程,也不需要分叉它。我只需要启动另一个php进程,当创建它的人退出时,不会收到SIGINT。 (我不确定守护进程与从终端分离的进程有什么不同?) – Dalius

+0

再次检查我的示例。这不是你想要的吗? ;)守护进程唯一的区别是它不会永远运行,但会在父亲出口时被杀死。 – hek2mgl

+0

基本上是的,但尝试在一个简单的函数中实现,返回true或false。 (它不能阻止)。我不希望新的进程被杀死,它会退出。 – Dalius

5

提供您的当前用户有足够的权限这样做,这应该可能与exec和类似:

/* 
/Start your child (otherscript.php) 
*/ 
function startMyScript() { 
    exec('nohup php otherscript.php > nohup.out & > /dev/null'); 
} 

/* 
/Kill the script (otherscript.php) 
/NB: only kills one process at the time, otherwise simply expand to 
/loop over all complete exec() output rows 
*/ 
function stopMyScript() { 
    exec('ps a | grep otherscript.php | grep -v grep', $otherProcessInfo); 
    $otherProcessInfo = array_filter(explode(' ', $otherProcessInfo[0])); 
    $otherProcessId = $otherProcessInfo[0]; 
    exec("kill $otherProcessId"); 
} 

// ensure child is killed when parent php script/process exits 
register_shutdown_function('stopMyScript'); 

startMyScript(); 
+5

请做**不**再做这个:http://stackoverflow.com/review/suggested-edits/3201462这绝对不是如何堆栈溢出工作。你是方式,**方式**,排除别人的答案,并指出自己的答案。 – meagar

+0

道歉 - 没有双关语意。我的印象是S.O.对于这里没有不正确的信息非常认真,因此我只是建议删除hek2mgl的信息,这不能用exec()函数完成。 – Philzen

+2

投票是我们在这里对内容进行分类的方式。 – meagar

相关问题