나는이 오래된 스레드 알지만, 그것을 더 완전한 대답을 사용할 수 있습니다처럼 보였다. 이것은 일반적으로 PHP에서 여러 프로세스를 생성하는 방법입니다.
주의 사항 : PHP was meant to die. 의미는 몇 초 동안 실행 한 다음 종료하는 것을 의미합니다. 하지만 PHP에서의 가비지 정리는 먼 길을왔다. 조심해야한다. 예기치 않은 메모리 소비 또는 기타 이상한 현상이 있는지 프로세스를 모니터링하십시오. 당신이 그것을 설정하고 잊어 버리기 전에 잠시 동안 호크와 같은 모든 것을 보아라. 그리고 그때까지도, 때때로 프로세스를 한 번 확인하거나, 어떤 것이 어색 해지면 자동으로 알려주도록하십시오.
입력 할 때, github에도 올려 놓는 것이 좋습니다.
프로그램을 실행할 준비가되면 로그에서 tail -f를 사용하여 출력을 확인하는 것이 좋습니다.
<?php
/*
* date: 27-sep-2015
* auth: robert smith
* info: run a php daemon process
* lic : MIT License (see LICENSE.txt for details)
*/
$pwd = realpath("");
$daemon = array(
"log" => $pwd."/service.log",
"errorLog" => $pwd."/service.error.log",
"pid_file" => $pwd."/",
"pid" => "",
"stdout" => NULL,
"stderr" => NULL,
"callback" => array("myProcessA", "myProcessB")
);
/*
* main (spawn new process)
*/
foreach ($daemon["callback"] as $k => &$v)
{
$pid = pcntl_fork();
if ($pid < 0)
exit("fork failed: unable to fork\n");
if ($pid == 0)
spawnChores($daemon, $v);
}
exit("fork succeeded, spawning process\n");
/*
* end main
*/
/*
* functions
*/
function spawnChores(&$daemon, &$callback)
{
// become own session
$sid = posix_setsid();
if ($sid < 0)
exit("fork failed: unable to become a session leader\n");
// set working directory as root (so files & dirs are not locked because of process)
chdir("/");
// close open parent file descriptors system STDIN, STDOUT, STDERR
fclose(STDIN);
fclose(STDOUT);
fclose(STDERR);
// setup custom file descriptors
$daemon["stdout"] = fopen($daemon["log"], "ab");
$daemon["stderr"] = fopen($daemon["errorLog"], "ab");
// publish pid
$daemon["pid"] = sprintf("%d", getmypid());
file_put_contents($daemon["pid_file"].$callback.".pid", $daemon["pid"]."\n");
// publish start message to log
fprintf($daemon["stdout"], "%s daemon %s started with pid %s\n", date("Y-M-d H:i:s"), $callback, $daemon["pid"]);
call_user_func($callback, $daemon);
// publish finish message to log
fprintf($daemon["stdout"], "%s daemon %s terminated with pid %s\n", date("Y-M-d H:i:s"), $callback, $daemon["pid"]);
exit(0);
}
function myProcessA(&$daemon)
{
$run_for_seconds = 30;
for($i=0; $i<$run_for_seconds; $i++)
{
fprintf($daemon["stdout"], "Just being a process, %s, for %d more seconds\n", __FUNCTION__, $run_for_seconds - $i);
sleep(1);
}
}
function myProcessB(&$daemon)
{
$run_for_seconds = 30;
for($i=0; $i<$run_for_seconds; $i++)
{
fprintf($daemon["stdout"], "Just being a process, %s, for %d/%d seconds\n", __FUNCTION__, $i, $run_for_seconds);
sleep(1);
}
}
?>
이런 종류의 것은 실제로 PHP가 의도 한 것이거나 그렇지 않습니다. 포킹 프로세스는 스레드를 생성하는 것보다 훨씬 비쌉니다. 이는 일반적으로 수행되는 방식입니다. – cletus
파이썬에서 스레드로 쉽게이 작업을 수행 할 수 있습니다. 특정 이유로 PHP 만 사용할 수있는 유일한 옵션입니다. – mmattax
글쎄 파이썬은 멀티 쓰레드 코드와 관련된 문제가 있습니다. 특히 CPython의 GIL이 그 중 하나입니다. Jython/IronPython에는이 문제가 없지만 컴파일해야한다고 생각합니다. – cletus