I came across the pcntl_fork
function. I saw that it creates a process
parallel, but I do not quite understand what it does.
No, there was a misunderstanding in your interpretation. The pcntl_fork
function does not create a parallel process, it forks the process and splits it into parent processes - > children.
It returns, on success, PID
of thread
pai
and 0
to PID
of filhos
. In the documentation there is a simple example of how it works:
$pid = pcntl_fork();
if ($pid == -1) {
die('could not fork');
} else if ($pid) {
// Processo pai
pcntl_wait($status); // Protege contra processos zumbis
} else {
// Processos filhos
}
As this answer in SOen , there are some advantages / disadvantages:
- Inter-process communication is possible, via serialized object in shared memory
- Synchronization through traffic lights is possible
-
File descriptors
and Database Conections
are shared and this can cause problems frequently. For example: Connections to DB
must be re-created every time a process is forked.
- The
pai
processes must wait for the filhos
processes to finish or the process will be left "zombies" running.
Remembering that PHP
is a scripting language and that "parallel" programming can be a nightmare and difficult to maintain.