开发者

Fork 3 children to run separate process each

Most of the examples I have seen only Print "I am a child with PID" . I am trying to fork 3 children, each child running 3 different processes. each o开发者_如何学Gof the children are separate C programs. Hence, I need to call them using exec() after fork() but my problem is in the syntax and how to reference each child because all child processes have pid =0.


Use getmypid() to get the pids in the children. The fork call returns 0 in the child processes:

for($i = 0; $i < 3; $i++) {
   $pid = pcntl_fork();
   if ($pid == -1) {
        die("Fork failed on loop #$i");
   } else if ($pid == 0) {
        $mypid = getmypid(); // executes in the children
        exec(... whatever this child has to run ...);
   } else {
        ... executes in the parent
   }
}

Note that this in PHP, but the basic mechanics remain the same in pretty much any language that does fork().


followup:

...
} else if ($pid == 0) {
    $mypid = getmypid();
    switch ($i) {
         case 0:
             exec(... app #1 ...)
         case 1:
             exec(... app #2 ...)
         case 2:
             exec(... app #3 ...)
    }
} ...

Is how you'd start up your 3 apps. At the moment the parent script calls fork(), each child will end up with a different $i, so you can determine which child you're in by the value of $i.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜