| File: MultiProcessor.php Lines 2 to 21 | 
 | 
2 |  | 
 | 
3 | /** | 
 | 
4 |  * 並列実行ドライバ | 
 | 
5 |  * | 
 | 
6 |  * Linuxの fork&exec を利用したものなのでWindowsでは動作しない。 | 
 | 
7 |  * pcntl拡張が必要。 | 
 | 
8 |  * | 
 | 
9 |  * @uses pcntl | 
 | 
10 |  */ | 
 |  | class MultiProcessor | 
 | 
12 | { | 
 | 
13 |     /** | 
 | 
14 |      * 登録された子プロセスのリスト | 
 | 
15 |      * | 
 | 
16 |      * <pre> | 
 | 
17 |      * executable => PATH/TO/EXECUTABLE | 
 | 
18 |      * args => array(arg1, arg2...) | 
 | 
19 |      * </pre> | 
 | 
20 |      * @var array | 
 | 
21 |      */ | 
|   | 
| File: MultiProcessor.php Lines 56 to 75 | 
 | 
56 |         if(count($this->childProcesses) === 0) { | 
 | 
57 |             return false; | 
 | 
58 |         } | 
 | 
59 |  | 
 | 
60 |         // fork & exec | 
 | 
61 |         $this->startChildren(); | 
 | 
62 |  | 
 | 
63 |         // wait | 
 | 
64 |         $arrExited = array(); | 
 |  |         foreach($this->pids as $pid=>$dummy) { | 
 | 
66 |             pcntl_waitpid($pid, $status, WUNTRACED); | 
 | 
67 |             //echo $pid, ":", pcntl_wexitstatus($status), "\n"; | 
 | 
68 |             $arrExited[$pid] = pcntl_wexitstatus($status); | 
 | 
69 |         } | 
 | 
70 |  | 
 | 
71 |         foreach($arrExited as $pid=>$status) { | 
 | 
72 |             if($status !== 0) { | 
 | 
73 |                 return false; | 
 | 
74 |                 break; | 
 | 
75 |             } | 
|   | 
| File: MultiProcessor.php Lines 85 to 104 | 
 | 
85 |      * | 
 | 
86 |      * @param string $executableFullpath 実行可能ファイルのfullpath | 
 | 
87 |      * @param string[] $args (optional) 引数 | 
 | 
88 |      */ | 
 | 
89 |     public function addChild($executableFullpath, array $args=array()) { | 
 | 
90 |         $this->childProcesses[] = array('executable'=>$executableFullpath, 'args'=>$args); | 
 | 
91 |     } | 
 | 
92 |  | 
 | 
93 |     protected function startChildren() { | 
 |  |         $numOfChildren = count($this->childProcesses); | 
 | 
95 |  | 
 | 
96 |         foreach($this->childProcesses as $child) { | 
 | 
97 |             $childPid = $this->forkChild($child['executable'], $child['args']); | 
 | 
98 |             $this->pids[$childPid]['forked'] = true; | 
 | 
99 |             $this->pids[$childPid]['args'] = $child['args']; | 
 | 
100 |         } | 
 | 
101 |     } | 
 | 
102 |  | 
 | 
103 |     /** | 
 | 
104 |      * fork & exec | 
|   | 
| File: MultiProcessor.php Lines 115 to 128 | 
 | 
115 |             throw new \Exception('Fork failed.'); | 
 | 
116 |         } elseif ($pid > 0) { | 
 | 
117 |             // Parent | 
 | 
118 |             //echo "Forking child...\n"; | 
 | 
119 |         } else { | 
 | 
120 |             // Child | 
 | 
121 |             pcntl_exec($executable, $args); | 
 | 
122 |  | 
 | 
123 |             // ここに来たということは pcntl_exec 失敗 | 
 |  |             exit(255); | 
 | 
125 |         } | 
 | 
126 |         return $pid; | 
 | 
127 |     } | 
 | 
128 | } | 
|   |