使用php的`pcntl_fork()`函数创建子进程,让每个子进程独立计算一个文件的哈希值,主进程负责收集结果。通过循环遍历文件列表,为每个文件派生一个子进程,子进程中调用`hash_file()`完成计算并输出结果,主进程利用`pcntl_waitpid()`等待所有子进程结束以回收资源。

如何确保子进程正确返回哈希值而不阻塞主进程
子进程在计算完成后应直接退出或向标准输出打印结果,主进程通过`pcntl_waitpid()`获取子进程的退出状态。为了避免主进程被挂起,必须显式调用等待函数。如果子进程数量较多,可以分批处理或使用信号量控制并发数,但在基础实现中,逐个等待是确保数据完整性的最简单方式。

$files = ['file1.txt', 'file2.txt'];
$results = [];
$children = [];
foreach ($files as $index => $file) {
$pid = pcntl_fork();
if ($pid == -1) {
die('Fork failed');
} elseif ($pid === 0) {
// Child process
$hash = hash_file('sha256', $file);
echo "{$file}: {$hash}\n";
exit(0);
} else {
// Parent process
$children[$pid] = $file;
}
}
// Wait for all children
foreach ($children as $pid => $file) {
$status = null;
pcntl_waitpid($pid, $status);
}
如何处理文件不存在或权限不足导致的异常
在子进程中执行`hash_file()`前,应先检查文件是否存在且可读。如果文件缺失或无权限,`hash_file()`会抛出警告并返回`false`。子进程应捕获这些情况,输出错误信息而非空哈希,并确保退出码非零以便主进程识别失败任务。主进程在等待时可以检查退出状态,从而区分成功与失败的计算任务。
使用官方Model Context Protocol PHP SDK将PHP应用程序功能暴露为MCP工具、资源和提示,用于代理工作流。
立即学习“PHP免费学习笔记(深入)”;

$files = ['valid.txt', 'missing.txt'];
$children = [];
foreach ($files as $file) {
$pid = pcntl_fork();
if ($pid == -1) {
die('Fork failed');
} elseif ($pid === 0) {
if (!is_readable($file)) {
echo "Error: Cannot read {$file}\n";
exit(1);
}
$hash = hash_file('sha256', $file);
if ($hash === false) {
echo "Error: Hash calculation failed for {$file}\n";
exit(1);
}
echo "{$file}: {$hash}\n";
exit(0);
} else {
$children[$pid] = $file;
}
}
foreach ($children as $pid => $file) {
$status = null;
pcntl_waitpid($pid, $status);
if (pcntl_wexitstatus($status) !== 0) {
echo "Failed to process {$file}\n";
}
}
基于程序中某个输入、条件或结果的具体问题
当文件列表为空时,程序不会进入循环,因此不会创建任何子进程,主进程直接结束。这种情况下,`$children`数组为空,等待循环也不会执行,程序行为符合预期,不会产生错误或阻塞。这种边界条件的处理确保了程序的健壮性,即使没有任务需要并行处理,脚本也能正常退出。


















