CakeFest 2024: The Official CakePHP Conference

Введение

Поддержка управления процессами в PHP реализует Unix-стиль создания процессов, запуска программ, обработки сигналов и остановки процессов. Управление процессами должно быть ОТКЛЮЧЕНО в окружении веб-сервера и результат будет непредсказуем, если функции управления процессами будут использованы в окружении такого веб-сервера. (На практике это значит, что pcntl можно использовать только в CLI и CGI, но не в apache mod_php)

Настоящая документация предназначена для объяснения основ использования каждой из функций управления процессами. Для более детального ознакомления с информацией об управлении Unix-процессами рекомендуется обратиться к вашему системному руководству, включая fork(2), waitpid(2) и signal(2) или к полному справочнику такому как "UNIX. Профессиональное программирование" У. Ричарда Стивенса (Advanced Programming in the UNIX Environment by W. Richard Stevens (Addison-Wesley).

PCNTL, на данный момент, использует "тики" как механизм обработки callback-функций, который значительно быстрее чем предыдущий механизм. Это изменение семантически похоже на использование "user ticks". Вы используете инструкцию declare(), чтобы задать расположение в программе, в котором callback-функции тика могут быть выполнены. Это позволяет минимизировать накладные расходы на обработку асинхронных событий. В прошлом, компиляция PHP со включённым pcntl всегда приводила к появлению этих накладных расходов, вне зависимости от того, использует ваш скрипт pcntl или нет.

Замечание: Для Windows-платформ этот модуль недоступен.

add a note

User Contributed Notes 3 notes

up
49
sean dot kelly at mediatile dot com
12 years ago
The following statement left me searching for answers for about a day before I finally clued in:

"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."

At least for PHP 5.3.8 which I am using, and who knows how far back, it's not a matter of "should not", it's "can not". Even though I have compiled in PCNTL with --enable-pcntl, it turns out that it only compiles in to the CLI version of PHP, not the Apache module. As a result, I spent many hours trying to track down why function_exists('pcntl_fork') was returning false even though it compiled correctly. It turns out it returns true just fine from the CLI, and only returns false for HTTP requests. The same is true of ALL of the pcntl_*() functions.
up
5
InvisibleSmiley
3 years ago
The disabling of pcntl functions not only affects Apache servers but any non-CLI setup, e.g. nginx with PHP-FPM.

You can tell by issuing phpinfo() and looking at "disable_functions" in the Core section of the output.

It's also worth noting that this behavior can be quite misleading when you call one of the pcntl functions in a namespaced context. For example you may get:

"Call to undefined function some\custom\namespace\pcntl_signal()"

when calling pcntl_signal from a method within a namespaced class. Your first instinct may be to add a leading backslash, but that won't solve the problem. You need to check whether the function exists at runtime, unless the code is only ever executed from the CLI.
up
12
Rick Sustek
7 years ago
Actually it makes perfect sense why process control features are not supported for the Apache module. The Apache HTTP server is the chief process. It invokes the PHP module when steered to PHP by the resource requested (e.g. http://foo.php) It invokes the PHP module, typically on a new thread or a pooled thread. The PHP module then runs your script, but Apache server is still the owning process.

In this execution model, the job of your PHP script is generally to go about its business as fast as possible and return. This allows the Apache daemon to do something else useful with the thread it let you borrow. Yes, some scripts take longer to do their duty than others, but blocking the thread for extended periods is usually frowned upon.

If your script was allowed to mess with the signal handlers of the running process, it would be messing with the Apache daemon itself! That daemon has already installed signal handlers for its own use. It is just plain sense not to allow the process control operations in this context.
To Top