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 114 to 127 |
|
114 | throw new Exception('Fork failed.'); |
|
115 | } else if ($pid > 0) { |
|
116 | // Parent |
|
117 | //echo "Forking child...\n"; |
|
118 | } else { |
|
119 | // Child |
|
120 | pcntl_exec($executable, $args); |
|
121 | |
|
122 | // ここに来たということは pcntl_exec 失敗 |
| | exit(255); |
|
124 | } |
|
125 | return $pid; |
|
126 | } |
|
127 | } |
|