What is the pcntl_fork function for?

Asked

Viewed 638 times

8

I was looking for some solution in PHP, where I could run a script without waiting for a certain function that processes time-consuming things to be expected to finish the execution of it.

I came across the function pcntl_fork. I saw that she creates a parallel process, but I didn’t quite understand what she does.

Could someone give me details of this function?

  • I found out that this contraption doesn’t work with Apache :\

  • You want to use the correct pthread library?

  • @Everson yes, too bad it doesn’t seem to exist this pro apache.

  • Actually there is the Pthread library, I even use it here. But only for sending email. I never used it directly in the application. But if you want I can put as an answer how to use this library.

  • @Everson might be. I got it to install it :\

1 answer

4


I came across the function pcntl_fork. I saw that she creates a process parallel, but I don’t quite understand what she does.

No, there was a misunderstanding in your interpretation. The function pcntl_fork does not create a parallel process, it forks the process and divides it into parent -> child processes.

It returns, in case of success, the PID of thread pai and 0 to the 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
}

In accordance with this answer in Soen, there are some advantages/disadvantages:

  • Communication between processes is possible, via serialized object in shared memory
  • Synchronization through traffic lights it is possible
  • File descriptors and Database Conections are shared and this can cause problems frequently. For example: Connections with DB must be recreated every time a process is forked.
  • The processes pai must wait for the completion of the processes filhos or "zombie" processes will be left running.

Remembering that PHP is a scripting language and that "parallel" programming can be a nightmare and difficult to maintain.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.