我正在使用pcntl
(http://php.net/manual/ro/book.pcntl.php)为wordpress系统开发多线程脚本,以生成并行工作的子进程。
当我创建子进程时,我需要再次返回进程ID以进行检查,但在我的foreach结构array_push()
中却无法正常工作。
为了测试pcntl
和fork
,我使用了这个示例https://gist.github.com/nicksantamaria/21dce5ff2a6640cdff76ce7bc57d2981
我的功能:
$tasks = [
"fetch_remote_data",
"post_async_updates",
"clear_caches",
"notify_admin",
];
$child_pid = [];
$i = 0;
echo "PARENT PROCESS ID => " . getmypid() . PHP_EOL;
foreach ($tasks as $task) {
$pid = pcntl_fork();
if ($pid == -1) {
exit("Error forking...\n");
}
elseif ($pid == 0) {
$my_pid = getmypid();
array_push($child_pid , $my_pid);
echo 'PARTIAL CHILD IDS ARRAY' . PHP_EOL;
print_r($child_pid);
echo "My task '$task' ID is $my_pid \r\n";
echo "Starting task: ${task}\n";
//return_child_process_id($my_pid, $i);
execute_task($task, $i);
exit();
}
$i++;
}
while(pcntl_waitpid(0, $status) != -1);
echo "Do stuff after all parallel execution is complete.\n";
print_r($child_pid);
echo 'Child Id: ' . PHP_EOL;
function execute_task($task_id, $i) {
echo "Starting task: ${task_id}\n";
$execution_time = rand(5, 10);
sleep($execution_time);
$return = pcntl_get_last_error();
echo "Completed task: ${task_id}. Key ID IS $i , with the error: ". $return ." => " . pcntl_strerror($return) . PHP_EOL;
}
但是我回到了外壳中。
为什么我的array_push()
无法正常工作,而我的$child_pid
却空着?
更新
我已经解决了使用外部文件保存过程ID的问题:
$fp = fopen('data.txt', 'a');
fwrite($fp, $mypid . PHP_EOL);
fclose($fp);