首先需要安装pcntl_ 拓展
PHP -M 查看是否存在这两个文件
测试文件 test.php
header('content-type:text/html;charset=utf-8' );
// 必须加载扩展
if (!function_exists("pcntl_fork")) {
die("pcntl extention is must !");
}
$ppid = posix_getpid();
$pid = pcntl_fork();
printf("\n");
if ($pid == -1) {
throw new Exception('fork子进程失败!');
} elseif ($pid > 0) {
cli_set_process_title("我是父进程,我的进程id是{$ppid}."); //父进程名称
while (true)
{
echo "我是父进程 ID =".$ppid;
printf("\n");
sleep(3);
}
} else {
$cpid = posix_getpid();
cli_set_process_title("我是{$ppid}的子进程,我的进程id是{$cpid}.");//子进程名称
while (true)
{
echo "我是子进程 ID=".$cpid;
printf("\n");
sleep(3);
}
}
?>
运行PHP index.php就可以看到脚本线程的效果了