PCNTL Multi-process

Source: Internet
Author: User

code

!--? Php$archildid = Array (), for ($i = 0; $i; $i + +) {$iPid = Pcntl_fork (); if ($iP id = =-1) {Die (& #39, can\& #39; t be forked.& #39;);} if ($iPid) {# main process logic $arChildId [] = $iPid;}  else {# child process logic $iPid = Posix_getpid ();    # Gets the ID of the child process $iSeconds = rand (5, 30); Echo & #39; * Process & #39;. $iPid. & #39; was created, and Executed, and Sleep & #39;. $iSeconds.    Php_eol;    Excuteprocess ($iPid, $iSeconds); Exit ();}}    while (count ($arChildId)--> 0) {foreach ($arChildId as $iKey = = $iPid) {$res = Pcntl_waitpid ($iPid, $status, Wnohang);        if ($res = =-1 | | $res > 0) {unset ($arChildId [$iKey]); Echo ' * Sub process: '. $iPid. ' Exited with '. $status.    Php_eol; The logical function excuteprocess ($iPid, $iSeconds) {file_put_contents ('./log/'. $iPid.}}}#) Execution of the child process. Log ', $iPid. Php_eol, File_append); sleep ($iSeconds);}? 

run result

* Process 16163 was created, and Executed, and sleep 11* process 16164 was created, and Executed, and sleep 21* process 16 165 was created, and Executed, and sleep 24* process 16166 is created, and Executed, and sleep 27* Process 16167 was Crea Ted, and Executed, and sleep 8* process 16168 is created, and Executed, and sleep 14* Process 16169 was created, and Exec Uted, and sleep 14* process 16170 was created, and Executed, and sleep 26* process 16171 is created, and Executed, and Sl  Eep 20* Process 16172 was created, and Executed, and Sleep 21* Sub process:16167 exited with 0* Sub process:16163 exited With 0* Sub process:16169 exited with 0* Sub process:16168 exited with 0* Sub process:16171 exited with 0* sub process : 16164 exited with 0* Sub process:16172 exited with 0* Sub process:16165 exited with 0* sub process:16170 exited with 0* Sub process:16166 exited with 0
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.