PHP:pcntl_fork() 的真正作用是什么?

标签 php apache thread-safety fork process-control

PHP 的 pcntl_fork 函数应该像 C 中的标准 fork 函数一样 fork 一个进程。
但我想知道这个函数是否真的 fork 了进程,或者它是否以不同的方式模拟了该行为。
如果它真的 fork 了这个进程,那么它是哪个进程就很清楚了:Apache 的子进程之一。
只要 Apache 使用 prefork MPM(即每个请求一个进程)就可以了。
但是如果 Apache 使用 worker MPM 会发生什么?
当使用 worker MPM 时,每个 Apache 子进程都包含许多线程,每个线程处理不同的 HTTP 请求。所以如果你在那种情况下 fork 进程,我什至无法想象所有这些线程和正在服务的请求会发生什么。
因此,如果 pcntl_fork() 真的 fork 了进程,那么我认为如果您将 Apache 设置为使用 worker MPM,则使用此函数不是一个好主意。

专家怎么说?我是在讲道理,还是在胡说八道?

最佳答案

pcntl_fork可能会像您想象的那样工作:它会 fork 当前进程,就像 C 函数 fork 所做的一样:

The pcntl_fork() function creates a child process that differs from the parent process only in its PID and PPID.
Please see your system's fork(2) man page for specific details as to how fork works on your system.


但是,引用 Introduction of the Process Control手册部分:

Process Control support in PHP implements the Unix style of process creation, program execution, signal handling and process termination.
Process Control should not be enabled within a web server environment and unexpected results may happen if any Process Control functions are used within a web server environment.

因此,您实际上不应该在通过 Apache 执行的 PHP 脚本中使用该函数:它只应在您的 PHP 脚本从命令行执行时使用。


而且,在开始使用该功能之前,请不要忘记:

Note: This extension is not available on Windows platforms.

关于PHP:pcntl_fork() 的真正作用是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2038586/

相关文章:

php - 没有设置 HttpOnly 标志的 session Cookie

java - 同步块(synchronized block)中的字符串不可变性和等待方法

c++ - 线程安全的延迟获取和释放

php - 如何从 4 列中有 3 列具有相同值的表中进行选择?

php - 从 PHP 访问 MySQL 的访问被拒绝

PHP - 如果是这种情况,什么都不做

php: session 与数据库

eclipse - 集成tomcat和eclipse却无法测试servlet?

php mkdir权限问题

Java:与 HikariDataSource 对象的并发