Skip to content

Create Robust Multiprocess Programs with Supervisor

Qing Zhao edited this page Mar 29, 2015 · 1 revision

There are many scenarios of multiprocess programming. Such as parallel task processing.

Nginx is a typical example. A master process runs with several children, like following.

|-+= 34843 root nginx: master process nginx
  |--- 34912 nobody nginx: worker process
  |--- 34913 nobody nginx: worker process
  \--- 34914 nobody nginx: worker process

Now, we have a similar case,but it's more simple. It’s programmed with Qpm\Supervisor.

/*
 Define what execute in child processes.
 In a child process, PID info would be printed per sec.
 After 10 secs, the child exits.
*/
$work = function() {
    $i = 10;
    while(--$i) {
            echo "[$i]PID:".posix_getpid()."\n";
            sleep(1);
    }
};
/* 
 Define the supervisor configuration.
 The worker is just $work.
 The quantity of parallel processes is 3. 
 It’s means that the supervisor would try to keep the alive
  children as 3. As a child exits, a same one would be forked.
 It’s just One-for-one supervision mode.
*/
$config = [‘worker'=>$run, 'quantity'=>3];
Comos\Qpm\Supervision\Supervisor::oneForOne($config)->start();

When the short script runs, a process tree is created.

\-+= 37063 php one_for_one_supervision.php
  |--- 37064 php one_for_one_supervision.php
  |--- 37065 php one_for_one_supervision.php
   \--- 37066 php one_for_one_supervision.php

It’s an easy way to create robust multi-process programs with Qpm\Supervisor, isn’t it?