cargomedia/CM — pull request #1239 by njam (2014-05-23 19:30:15+00:00)
Title: Send fork-result back to parent on wait()

@fauvel @tomaszdurka I wanted use process forking for faster image processing on the webserver.
Turns out that's not a good idea within php-fpm.
Nevertheless I think something along these lines might be useful (for CLI).
Basically when a process' fork()-workload has finished, I send back the return-value through a stream
to the parent process. Within that result I also contain the exception, if one was thrown. This allows
to process exceptions from forked processes.

What do you think?

Example usage:
```php
$process = CM_Process::getInstance();

for ($i = 0; $i < 3; $i++) {
$process->fork(function () use ($i) {
for ($t = 0; $t < 3; $t++) {
if ($t == 1 && $i == 0) {
throw new Exception('jo');
}
sleep(1);
echo "$i - $t\n";
}
return 'foo';
});
}

$resultList = $process->waitForChildren();
var_dump($resultList);
```

Output:
```
0 - 0
2 - 0
1 - 0
Exception: jo in /home/vagrant/fuboo/scripts/test.php on line 16
0. {main} /home/vagrant/fuboo/scripts/test.php:0
1. CM_Process->fork(Closure) /home/vagrant/fuboo/scripts/test.php:22
2. CM_Process_ForkHandler->runAndSendWorkload() /home/vagrant/CM/library/CM/Process.php:48
3. {closure}() /home/vagrant/CM/library/CM/Process/ForkHandler.php:46

2 - 1
1 - 1
2 - 2
1 - 2
array(3) {
[0] =>
class CM_Process_WorkloadResult#208 (2) {
private $_result =>
NULL
private $_exception =>
class CM_ExceptionHandling_SerializableException#207 (7) {
public $class =>
string(9) "Exception"
public $message =>
string(2) "jo"
public $line =>
int(16)
public $file =>
string(36) "/home/vagrant/fuboo/scripts/test.php"
public $trace =>
array(4) {
...
}
public $traceString =>
NULL
public $metaInfo =>
array(0) {
...
}
}
}
[1] =>
class CM_Process_WorkloadResult#213 (2) {
private $_result =>
string(3) "foo"
private $_exception =>
NULL
}
[2] =>
class CM_Process_WorkloadResult#209 (2) {
private $_result =>
string(3) "foo"
private $_exception =>
NULL
}
}
```