PHP的exec()
函数本身不支持多线程
然而,你可以使用其他方法来实现类似的功能。例如,你可以使用PHP的pcntl_fork()
函数来创建子进程。这允许你在父进程中执行一个命令,同时在子进程中执行另一个命令。请注意,pcntl_fork()
仅在UNIX-like系统(如Linux和macOS)上可用。
这是一个简单的示例:
$command) { exec($command, $output, $return_var); return $output; } // 父进程 $parent_output = runCommand("echo 'Parent process'"); echo "Parent process output: " . implode("\n", $parent_output) . PHP_EOL; // 子进程 $child_pid = pcntl_fork(); if ($child_pid == -1) { die("Failed to fork"); } elseif ($child_pid) { // 父进程继续执行其他任务 echo "Parent process continues..." . PHP_EOL; } else { // 子进程执行命令 $child_output = runCommand("echo 'Child process'"); echo "Child process output: " . implode("\n", $child_output) . PHP_EOL; exit(0); } ?>
这个示例中,我们定义了一个runCommand()
函数,它接受一个命令作为参数,并使用exec()
函数执行该命令。在主程序中,我们创建了一个子进程,并在其中执行了一个不同的命令。这样,我们就可以在同一个脚本中同时运行多个命令,从而实现类似多线程的功能。