我有 php7 CLI 守护进程,它连续解析文件大小超过 50M 的 json。我试图使用 pcntl_fork() 的单独进程将每 1000 个解析数据条目保存到 mysql,对于约 200k 行,它工作得很好。
然后我得到pcntl_fork(): 错误 35.
我认为发生这种情况是因为 mysql 插入变得比解析慢,这导致生成越来越多的分叉,直到 CentOS 6.3 无法再处理它。
有没有办法捕获此错误以诉诸单进程解析和保存?或者有没有办法检查子进程计数?
这是我根据@Sander Visser 评论所做的解决方案。关键部分是检查现有流程,如果流程太多,则采用相同的流程
class serialJsonReader{
const MAX_CHILD_PROCESSES = 50;
private $child_processes=[]; //will store alive child PIDs
private function flushCachedDataToStore() {
//resort to single process
if (count($this->child_processes) > self::MAX_CHILD_PROCESSES) {
$this->checkChildProcesses();
$this->storeCollectedData() //main work here
}
//use as much as possible
else {
$pid = pcntl_fork();
if (!$pid) {
$this->storeCollectedData(); //main work here
exit();
}
elseif ($pid == -1) {
die('could not fork');
}
else {
$this->child_processes[] = $pid;
$this->checkChildProcesses();
}
}
}
private function checkChildProcesses() {
if (count($this->child_processes) > self::MAX_CHILD_PROCESSES) {
foreach ($this->child_processes as $key => $pid) {
$res = pcntl_waitpid($pid, $status, WNOHANG);
// If the process has already exited
if ($res == -1 || $res > 0) {
unset($this->child_processes[$key]);
}
}
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)