2013-10-23 3 views
7

현재 내 솔루션은 다음과 같습니다 PHP : 분리 된 프로세스를 시작하는 방법은 무엇입니까?

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

및 file.php에

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

난 그냥 간부 인이 할 수있는 방법은 무엇입니까? 당신이 pcntl extension 설치 한 경우

+0

나는 그렇게 생각하지 않습니다. 아마도 그는 posix_setsid 예제가 도움이 될 수 있지만 fork()를 사용합니다. –

답변

5

은 어떤이는 것 exec() (도 shell_exec() 또는 system())


대해 수행 할 수 없습니다

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

프로세스를 대몬 비호 처리하고 싶지 않고 포크화할 필요가 없습니다. 난 그냥 그것을 만든 사람이 종료 될 때 SIGINT받지 못할 다른 PHP 프로세스를 시작해야합니다. (나는 데몬이 터미널에서 분리 된 프로세스와 어떻게 다른지 정말로 모르겠다.) – Dalius

+0

예제를 다시 확인하십시오. 니가 원하는게 아니야? ;) 데몬과의 유일한 차이점은 영원히 달리지는 않지만 아버지가 빠져 나갈 때 살해된다는 것입니다. – hek2mgl

+0

기본적으로 그렇습니다. 그러나이를 true 또는 false를 반환하는 간단한 함수로 구현해보십시오. (차단해서는 안됨). 그리고 나는 새로운 과정이 죽기를 원하지 않습니다, 그것은 스스로 끝낼 것입니다. – Dalius

5

현재 사용자에게 이렇게하려면 충분한 권한이 있어야합니다. 등으로 가능해야합니다.

/* 
/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

관련 문제