What is the purpose of the pcntl_fork function?

8

I was looking for some solution in PHP, where I could execute a script without waiting for a function that processes delayed things to be expected to finish executing it.

I came across the pcntl_fork function. I saw that it creates a parallel process, but I do not quite understand what it does.

Could anyone give me details of this function?

    
asked by anonymous 02.06.2017 / 16:09

1 answer

4
  

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.

    
05.06.2017 / 15:01