diff -Nru php-react-child-process-0.5.2/CHANGELOG.md php-react-child-process-0.6.1/CHANGELOG.md --- php-react-child-process-0.5.2/CHANGELOG.md 2018-01-18 14:53:06.000000000 +0000 +++ php-react-child-process-0.6.1/CHANGELOG.md 2019-02-15 13:48:16.000000000 +0000 @@ -1,5 +1,57 @@ # Changelog +## 0.6.1 (2019-02-15) + +* Feature / Fix: Improve error reporting when spawning child process fails. + (#73 by @clue) + +## 0.6.0 (2019-01-14) + +A major feature release with some minor API improvements! +This project now has limited Windows support and supports passing custom pipes +and file descriptors to the child process. + +This update involves a few minor BC breaks. We've tried hard to avoid BC breaks +where possible and minimize impact otherwise. We expect that most consumers of +this package will actually not be affected by any BC breaks, see below for more +details. + +* Feature / BC break: Support passing custom pipes and file descriptors to child process, + expose all standard I/O pipes in an array and remove unused Windows-only options. + (#62, #64 and #65 by @clue) + + > BC note: The optional `$options` parameter in the `Process` constructor + has been removed and a new `$fds` parameter has been added instead. The + previous `$options` parameter was Windows-only, available options were not + documented or referenced anywhere else in this library, so its actual + impact is expected to be relatively small. See the documentation and the + following changelog entry if you're looking for Windows support. + +* Feature: Support spawning child process on Windows without process I/O pipes. + (#67 by @clue) + +* Feature / BC break: Improve sigchild compatibility and support explicit configuration. + (#63 by @clue) + + ```php + // advanced: not recommended by default + Process::setSigchildEnabled(true); + ``` + + > BC note: The old public sigchild methods have been removed, but its + practical impact is believed to be relatively small due to the automatic detection. + +* Improve performance by prefixing all global functions calls with \ to skip + the look up and resolve process and go straight to the global function. + (#68 by @WyriHaximus) + +* Minor documentation improvements and docblock updates. + (#59 by @iamluc and #69 by @CharlotteDunois) + +* Improve test suite to test against PHP7.2 and PHP 7.3, improve HHVM compatibility, + add forward compatibility with PHPUnit 7 and run tests on Windows via Travis CI. + (#66 and #71 by @clue) + ## 0.5.2 (2018-01-18) * Feature: Detect "exit" immediately if last process pipe is closed diff -Nru php-react-child-process-0.5.2/composer.json php-react-child-process-0.6.1/composer.json --- php-react-child-process-0.5.2/composer.json 2018-01-18 14:53:06.000000000 +0000 +++ php-react-child-process-0.6.1/composer.json 2019-02-15 13:48:16.000000000 +0000 @@ -10,7 +10,8 @@ "react/stream": "^1.0 || ^0.7.6" }, "require-dev": { - "phpunit/phpunit": "^6.4 || ^5.7 || ^4.8.35", + "phpunit/phpunit": "^7.0 || ^6.4 || ^5.7 || ^4.8.35", + "react/socket": "^1.0", "sebastian/environment": "^3.0 || ^2.0 || ^1.0" }, "autoload": { diff -Nru php-react-child-process-0.5.2/debian/changelog php-react-child-process-0.6.1/debian/changelog --- php-react-child-process-0.5.2/debian/changelog 2018-12-03 22:59:27.000000000 +0000 +++ php-react-child-process-0.6.1/debian/changelog 2020-03-09 22:03:29.000000000 +0000 @@ -1,3 +1,10 @@ +php-react-child-process (0.6.1-1) unstable; urgency=medium + + * New upstream version. + * Bump Standards-Version (no changes needed). + + -- Dominik George Mon, 09 Mar 2020 23:03:29 +0100 + php-react-child-process (0.5.2-2) unstable; urgency=medium * Update dependencies. diff -Nru php-react-child-process-0.5.2/debian/control php-react-child-process-0.6.1/debian/control --- php-react-child-process-0.5.2/debian/control 2018-12-03 22:59:27.000000000 +0000 +++ php-react-child-process-0.6.1/debian/control 2020-03-09 22:03:29.000000000 +0000 @@ -4,7 +4,7 @@ Maintainer: Teckids Debian Task Force Uploaders: Thorsten Glaser , Dominik George Build-Depends: debhelper (>= 11~), pkg-php-tools (>= 1.7~) -Standards-Version: 4.2.1 +Standards-Version: 4.5.0 Homepage: https://github.com/reactphp/child-process Vcs-Git: https://salsa.debian.org/tdtf-team/php-react-child-process.git Vcs-Browser: https://salsa.debian.org/tdtf-team/php-react-child-process diff -Nru php-react-child-process-0.5.2/debian/patches/pkg-php-tools-deficiency-workaround.diff php-react-child-process-0.6.1/debian/patches/pkg-php-tools-deficiency-workaround.diff --- php-react-child-process-0.5.2/debian/patches/pkg-php-tools-deficiency-workaround.diff 2018-12-03 22:59:27.000000000 +0000 +++ php-react-child-process-0.6.1/debian/patches/pkg-php-tools-deficiency-workaround.diff 2020-03-09 22:03:29.000000000 +0000 @@ -15,4 +15,4 @@ + "react/stream": "^1.0" }, "require-dev": { - "phpunit/phpunit": "^6.4 || ^5.7 || ^4.8.35", + "phpunit/phpunit": "^7.0 || ^6.4 || ^5.7 || ^4.8.35", diff -Nru php-react-child-process-0.5.2/examples/01-stdio.php php-react-child-process-0.6.1/examples/01-stdio.php --- php-react-child-process-0.5.2/examples/01-stdio.php 2018-01-18 14:53:06.000000000 +0000 +++ php-react-child-process-0.6.1/examples/01-stdio.php 2019-02-15 13:48:16.000000000 +0000 @@ -5,6 +5,10 @@ require __DIR__ . '/../vendor/autoload.php'; +if (DIRECTORY_SEPARATOR === '\\') { + exit('Process pipes not supported on Windows' . PHP_EOL); +} + $loop = Factory::create(); $process = new Process('cat'); diff -Nru php-react-child-process-0.5.2/examples/02-race.php php-react-child-process-0.6.1/examples/02-race.php --- php-react-child-process-0.5.2/examples/02-race.php 2018-01-18 14:53:06.000000000 +0000 +++ php-react-child-process-0.6.1/examples/02-race.php 2019-02-15 13:48:16.000000000 +0000 @@ -5,6 +5,10 @@ require __DIR__ . '/../vendor/autoload.php'; +if (DIRECTORY_SEPARATOR === '\\') { + exit('Process pipes not supported on Windows' . PHP_EOL); +} + $loop = Factory::create(); $first = new Process('sleep 2; echo welt'); diff -Nru php-react-child-process-0.5.2/examples/03-stdout-stderr.php php-react-child-process-0.6.1/examples/03-stdout-stderr.php --- php-react-child-process-0.5.2/examples/03-stdout-stderr.php 2018-01-18 14:53:06.000000000 +0000 +++ php-react-child-process-0.6.1/examples/03-stdout-stderr.php 2019-02-15 13:48:16.000000000 +0000 @@ -5,6 +5,10 @@ require __DIR__ . '/../vendor/autoload.php'; +if (DIRECTORY_SEPARATOR === '\\') { + exit('Process pipes not supported on Windows' . PHP_EOL); +} + $loop = Factory::create(); $process = new Process('echo hallo;sleep 1;echo welt >&2;sleep 1;echo error;sleep 1;nope'); diff -Nru php-react-child-process-0.5.2/examples/04-terminate.php php-react-child-process-0.6.1/examples/04-terminate.php --- php-react-child-process-0.5.2/examples/04-terminate.php 2018-01-18 14:53:06.000000000 +0000 +++ php-react-child-process-0.6.1/examples/04-terminate.php 2019-02-15 13:48:16.000000000 +0000 @@ -8,7 +8,7 @@ $loop = Factory::create(); // start a process that takes 10s to terminate -$process = new Process('sleep 10'); +$process = new Process('php -r "sleep(10);"', null, null, array()); $process->start($loop); // report when process exits @@ -18,9 +18,9 @@ // forcefully terminate process after 2s $loop->addTimer(2.0, function () use ($process) { - $process->stdin->close(); - $process->stdout->close(); - $process->stderr->close(); + foreach ($process->pipes as $pipe) { + $pipe->close(); + } $process->terminate(); }); diff -Nru php-react-child-process-0.5.2/examples/11-benchmark-read.php php-react-child-process-0.6.1/examples/11-benchmark-read.php --- php-react-child-process-0.5.2/examples/11-benchmark-read.php 2018-01-18 14:53:06.000000000 +0000 +++ php-react-child-process-0.6.1/examples/11-benchmark-read.php 2019-02-15 13:48:16.000000000 +0000 @@ -9,6 +9,10 @@ require __DIR__ . '/../vendor/autoload.php'; +if (DIRECTORY_SEPARATOR === '\\') { + exit('Process pipes not supported on Windows' . PHP_EOL); +} + $cmd = isset($argv[1]) ? implode(' ', array_slice($argv, 1)) : 'dd if=/dev/zero bs=1M count=1000'; $loop = Factory::create(); diff -Nru php-react-child-process-0.5.2/examples/12-benchmark-write.php php-react-child-process-0.6.1/examples/12-benchmark-write.php --- php-react-child-process-0.5.2/examples/12-benchmark-write.php 2018-01-18 14:53:06.000000000 +0000 +++ php-react-child-process-0.6.1/examples/12-benchmark-write.php 2019-02-15 13:48:16.000000000 +0000 @@ -2,10 +2,13 @@ use React\EventLoop\Factory; use React\ChildProcess\Process; -use React\Stream\Stream; require __DIR__ . '/../vendor/autoload.php'; +if (DIRECTORY_SEPARATOR === '\\') { + exit('Process pipes not supported on Windows' . PHP_EOL); +} + $loop = Factory::create(); $info = new React\Stream\WritableResourceStream(STDERR, $loop); diff -Nru php-react-child-process-0.5.2/examples/13-benchmark-throughput.php php-react-child-process-0.6.1/examples/13-benchmark-throughput.php --- php-react-child-process-0.5.2/examples/13-benchmark-throughput.php 2018-01-18 14:53:06.000000000 +0000 +++ php-react-child-process-0.6.1/examples/13-benchmark-throughput.php 2019-02-15 13:48:16.000000000 +0000 @@ -2,10 +2,13 @@ use React\EventLoop\Factory; use React\ChildProcess\Process; -use React\Stream\Stream; require __DIR__ . '/../vendor/autoload.php'; +if (DIRECTORY_SEPARATOR === '\\') { + exit('Process pipes not supported on Windows' . PHP_EOL); +} + $loop = Factory::create(); $info = new React\Stream\WritableResourceStream(STDERR, $loop); diff -Nru php-react-child-process-0.5.2/examples/21-fds.php php-react-child-process-0.6.1/examples/21-fds.php --- php-react-child-process-0.5.2/examples/21-fds.php 1970-01-01 00:00:00.000000000 +0000 +++ php-react-child-process-0.6.1/examples/21-fds.php 2019-02-15 13:48:16.000000000 +0000 @@ -0,0 +1,27 @@ +&- 2>&-;exec ls -la /proc/self/fd', null, null, array( + 1 => array('pipe', 'w') +)); +$process->start($loop); + +$process->stdout->on('data', function ($chunk) { + echo $chunk; +}); + +$process->on('exit', function ($code) { + echo 'EXIT with code ' . $code . PHP_EOL; +}); + +$loop->run(); diff -Nru php-react-child-process-0.5.2/examples/22-race-exit.php php-react-child-process-0.6.1/examples/22-race-exit.php --- php-react-child-process-0.5.2/examples/22-race-exit.php 1970-01-01 00:00:00.000000000 +0000 +++ php-react-child-process-0.6.1/examples/22-race-exit.php 2019-02-15 13:48:16.000000000 +0000 @@ -0,0 +1,24 @@ +start($loop); + +$first->on('exit', function ($code) { + echo 'First closed ' . $code . PHP_EOL; +}); + +$second = new Process('php -r "sleep(1);"', null, null, array()); +$second->start($loop); + +$second->on('exit', function ($code) { + echo 'Second closed ' . $code . PHP_EOL; +}); + +$loop->run(); diff -Nru php-react-child-process-0.5.2/examples/23-forward-socket.php php-react-child-process-0.6.1/examples/23-forward-socket.php --- php-react-child-process-0.5.2/examples/23-forward-socket.php 1970-01-01 00:00:00.000000000 +0000 +++ php-react-child-process-0.6.1/examples/23-forward-socket.php 2019-02-15 13:48:16.000000000 +0000 @@ -0,0 +1,42 @@ +on('connection', function (React\Socket\ConnectionInterface $connection) { + $connection->on('data', function ($chunk) { + // escape control codes (useful in case encoding or binary data is not working as expected) + // $chunk = addcslashes($chunk,"\0..\37!@\177..\377"); + + // convert default code page 850 to UTF-8 (German Windows in this case) + $chunk = iconv('CP850','UTF-8', $chunk); + + echo $chunk; + }); +}); + +$command = 'php -r "echo 1;sleep(1);echo 2;sleep(1);echo 3;"'; +// $command = 'ping google.com'; +// $command = 'C:\Windows\System32\ping google.com'; + +// use stream redirections to consume output of child process in another helper process and forward to socket +$code = '$s=stream_socket_client($argv[1]);do{fwrite($s,$d=fread(STDIN, 8192));}while(isset($d[0]));'; +$process = new Process( + $command . ' | php -r ' . escapeshellarg($code) . ' ' . $server->getAddress(), + null, + null, + array() +); +$process->start($loop); + +$process->on('exit', function ($code) use ($server) { + $server->close(); + echo PHP_EOL . 'Process closed ' . $code . PHP_EOL; +}); + +$loop->run(); diff -Nru php-react-child-process-0.5.2/phpunit.xml.dist php-react-child-process-0.6.1/phpunit.xml.dist --- php-react-child-process-0.5.2/phpunit.xml.dist 2018-01-18 14:53:06.000000000 +0000 +++ php-react-child-process-0.6.1/phpunit.xml.dist 2019-02-15 13:48:16.000000000 +0000 @@ -8,7 +8,6 @@ convertWarningsToExceptions="true" processIsolation="false" stopOnFailure="false" - syntaxCheck="false" bootstrap="vendor/autoload.php" > diff -Nru php-react-child-process-0.5.2/README.md php-react-child-process-0.6.1/README.md --- php-react-child-process-0.5.2/README.md 2018-01-18 14:53:06.000000000 +0000 +++ php-react-child-process-0.6.1/README.md 2019-02-15 13:48:16.000000000 +0000 @@ -19,6 +19,7 @@ * [Stream Properties](#stream-properties) * [Command](#command) * [Termination](#termination) + * [Custom pipes](#custom-pipes) * [Sigchild Compatibility](#sigchild-compatibility) * [Windows Compatibility](#windows-compatibility) * [Install](#install) @@ -52,19 +53,35 @@ Once a process is started, its I/O streams will be constructed as instances of `React\Stream\ReadableStreamInterface` and `React\Stream\WritableStreamInterface`. -Before `start()` is called, these properties are `null`.Once a process terminates, +Before `start()` is called, these properties are not set. Once a process terminates, the streams will become closed but not unset. -* `$stdin` -* `$stdout` -* `$stderr` +Following common Unix conventions, this library will start each child process +with the three pipes matching the standard I/O streams as given below by default. +You can use the named references for common use cases or access these as an +array with all three pipes. + +* `$stdin` or `$pipes[0]` is a `WritableStreamInterface` +* `$stdout` or `$pipes[1]` is a `ReadableStreamInterface` +* `$stderr` or `$pipes[2]` is a `ReadableStreamInterface` + +Note that this default configuration may be overridden by explicitly passing +[custom pipes](#custom-pipes), in which case they may not be set or be assigned +different values. In particular, note that [Windows support](#windows-compatibility) +is limited in that it doesn't support non-blocking STDIO pipes. The `$pipes` +array will always contain references to all pipes as configured and the standard +I/O references will always be set to reference the pipes matching the above +conventions. See [custom pipes](#custom-pipes) for more details. -Each of these implement the underlying +Because each of these implement the underlying [`ReadableStreamInterface`](https://github.com/reactphp/stream#readablestreaminterface) or -[`WritableStreamInterface`](https://github.com/reactphp/stream#writablestreaminterface) and +[`WritableStreamInterface`](https://github.com/reactphp/stream#writablestreaminterface), you can use any of their events and methods as usual: ```php +$process = new Process($command); +$process->start($loop); + $process->stdout->on('data', function ($chunk) { echo $chunk; }); @@ -99,9 +116,26 @@ $process->start($loop); ``` +The command line string usually consists of a whitespace-separated list with +your main executable bin and any number of arguments. Special care should be +taken to escape or quote any arguments, escpecially if you pass any user input +along. Likewise, keep in mind that especially on Windows, it is rather common to +have path names containing spaces and other special characters. If you want to +run a binary like this, you will have to ensure this is quoted as a single +argument using `escapeshellarg()` like this: + +```php +$bin = 'C:\\Program files (x86)\\PHP\\php.exe'; +$file = 'C:\\Users\\me\\Desktop\\Application\\main.php'; + +$process = new Process(escapeshellarg($bin) . ' ' . escapeshellarg($file)); +$process->start($loop); +``` + By default, PHP will launch processes by wrapping the given command line string -in a `sh` command, so that the above example will actually execute -`sh -c echo test` under the hood. +in a `sh` command on Unix, so that the first example will actually execute +`sh -c echo test` under the hood on Unix. On Windows, it will not launch +processes by wrapping them in a shell. This is a very useful feature because it does not only allow you to pass single commands, but actually allows you to pass any kind of shell command line and @@ -115,6 +149,12 @@ $process->start($loop); ``` +> Note that [Windows support](#windows-compatibility) is limited in that it + doesn't support STDIO streams at all and also that processes will not be run + in a wrapping shell by default. If you want to run a shell built-in function + such as `echo hello` or `sleep 10`, you may have to prefix your command line + with an explicit shell like `cmd /c echo hello`. + In other words, the underlying shell is responsible for managing this command line and launching the individual sub-commands and connecting their STDIO streams as appropriate. @@ -145,7 +185,7 @@ }); ``` -Keep in mind that PHP uses the shell wrapper for ALL command lines. +Keep in mind that PHP uses the shell wrapper for ALL command lines on Unix. While this may seem reasonable for more complex command lines, this actually also applies to running the most simple single command: @@ -154,7 +194,7 @@ $process->start($loop); ``` -This will actually spawn a command hierarchy similar to this: +This will actually spawn a command hierarchy similar to this on Unix: ``` 5480 … \_ php example.php @@ -167,8 +207,8 @@ in many cases. If you do not want this wrapping shell process to show up, you can simply -prepend the command string with `exec`, which will cause the wrapping shell -process to be replaced by our process: +prepend the command string with `exec` on Unix platforms, which will cause the +wrapping shell process to be replaced by our process: ```php $process = new Process('exec yes'); @@ -193,8 +233,8 @@ shell. If you pass a complete command line (or are unsure), you SHOULD most likely keep the wrapping shell. -If you want to pass an invidual command only, you MAY want to consider -prepending the command string with `exec` to avoid the wrapping shell. +If you're running on Unix and you want to pass an invidual command only, you MAY +want to consider prepending the command string with `exec` to avoid the wrapping shell. ### Termination @@ -255,10 +295,10 @@ $process->start($loop); $loop->addTimer(2.0, function () use ($process) { - $process->stdin->close(); - $process->stout->close(); - $process->stderr->close(); - $process->terminate(SIGKILL); + foreach ($process->pipes as $pipe) { + $pipe->close(); + } + $process->terminate(); }); ``` @@ -293,29 +333,231 @@ such as first trying a soft-close and then applying a force-close after a timeout. +### Custom pipes + +Following common Unix conventions, this library will start each child process +with the three pipes matching the standard I/O streams by default. For more +advanced use cases it may be useful to pass in custom pipes, such as explicitly +passing additional file descriptors (FDs) or overriding default process pipes. + +Note that passing custom pipes is considered advanced usage and requires a +more in-depth understanding of Unix file descriptors and how they are inherited +to child processes and shared in multi-processing applications. + +If you do not want to use the default standard I/O pipes, you can explicitly +pass an array containing the file descriptor specification to the constructor +like this: + +```php +$fds = array( + // standard I/O pipes for stdin/stdout/stderr + 0 => array('pipe', 'r'), + 1 => array('pipe', 'w'), + 2 => array('pipe', 'w'), + + // example FDs for files or open resources + 4 => array('file', '/dev/null', 'r'), + 6 => fopen('log.txt','a'), + 8 => STDERR, + + // example FDs for sockets + 10 => fsockopen('localhost', 8080), + 12 => stream_socket_server('tcp://0.0.0.0:4711') +); + +$process = new Process($cmd, null, null, $fds); +$process->start($loop); +``` + +Unless your use case has special requirements that demand otherwise, you're +highly recommended to (at least) pass in the standard I/O pipes as given above. +The file descriptor specification accepts arguments in the exact same format +as the underlying [`proc_open()`](http://php.net/proc_open) function. + +Once the process is started, the `$pipes` array will always contain references to +all pipes as configured and the standard I/O references will always be set to +reference the pipes matching common Unix conventions. This library supports any +number of pipes and additional file descriptors, but many common applications +being run as a child process will expect that the parent process properly +assigns these file descriptors. + ### Sigchild Compatibility -When PHP has been compiled with the `--enabled-sigchild` option, a child -process' exit code cannot be reliably determined via `proc_close()` or -`proc_get_status()`. Instead, we execute the child process with a fourth pipe -and use that to retrieve its exit code. - -This behavior is used by default and only when necessary. It may be manually -disabled by calling `setEnhanceSigchildCompatibility(false)` on the Process -before it is started, in which case the `exit` event may receive `null` instead -of the actual exit code. +Internally, this project uses a work-around to improve compatibility when PHP +has been compiled with the `--enable-sigchild` option. This should not affect most +installations as this configure option is not used by default and many +distributions (such as Debian and Ubuntu) are known to not use this by default. +Some installations that use [Oracle OCI8](http://php.net/manual/en/book.oci8.php) +may use this configure option to circumvent `defunct` processes. + +When PHP has been compiled with the `--enable-sigchild` option, a child process' +exit code cannot be reliably determined via `proc_close()` or `proc_get_status()`. +To work around this, we execute the child process with an additional pipe and +use that to retrieve its exit code. + +This work-around incurs some overhead, so we only trigger this when necessary +and when we detect that PHP has been compiled with the `--enable-sigchild` option. +Because PHP does not provide a way to reliably detect this option, we try to +inspect output of PHP's configure options from the `phpinfo()` function. + +The static `setSigchildEnabled(bool $sigchild): void` method can be used to +explicitly enable or disable this behavior like this: + +```php +// advanced: not recommended by default +Process::setSigchildEnabled(true); +``` + +Note that all processes instantiated after this method call will be affected. +If this work-around is disabled on an affected PHP installation, the `exit` +event may receive `null` instead of the actual exit code as described above. +Similarly, some distributions are known to omit the configure options from +`phpinfo()`, so automatic detection may fail to enable this work-around in some +cases. You may then enable this explicitly as given above. -**Note:** This functionality was taken from Symfony's +**Note:** The original functionality was taken from Symfony's [Process](https://github.com/symfony/process) compoment. ### Windows Compatibility -Due to the blocking nature of `STDIN`/`STDOUT`/`STDERR` pipes on Windows we can -not guarantee this package works as expected on Windows directly. As such when -instantiating `Process` it throws an exception when on native Windows. -However this package does work on [`Windows Subsystem for Linux`](https://en.wikipedia.org/wiki/Windows_Subsystem_for_Linux) -(or WSL) without issues. We suggest [installing WSL](https://msdn.microsoft.com/en-us/commandline/wsl/install_guide) -when you want to run this package on Windows. +Due to platform constraints, this library provides only limited support for +spawning child processes on Windows. In particular, PHP does not allow accessing +standard I/O pipes without blocking. As such, this project will not allow +constructing a child process with the default process pipes and will instead +throw a `LogicException` on Windows by default: + +```php +// throws LogicException on Windows +$process = new Process('ping example.com'); +$process->start($loop); +``` + +There are a number of alternatives and workarounds as detailed below if you want +to run a child process on Windows, each with its own set of pros and cons: + +* This package does work on + [`Windows Subsystem for Linux`](https://en.wikipedia.org/wiki/Windows_Subsystem_for_Linux) + (or WSL) without issues. When you are in control over how your application is + deployed, we recommend [installing WSL](https://msdn.microsoft.com/en-us/commandline/wsl/install_guide) + when you want to run this package on Windows. + +* If you only care about the exit code of a child process to check if its + execution was successful, you can use [custom pipes](#custom-pipes) to omit + any standard I/O pipes like this: + + ```php + $process = new Process('ping example.com', null, null, array()); + $process->start($loop); + + $process->on('exit', function ($exitcode) { + echo 'exit with ' . $exitcode . PHP_EOL; + }); + ``` + + Similarly, this is also useful if your child process communicates over + sockets with remote servers or even your parent process using the + [Socket component](https://github.com/reactphp/socket). This is usually + considered the best alternative if you have control over how your child + process communicates with the parent process. + +* If you only care about command output after the child process has been + executed, you can use [custom pipes](#custom-pipes) to configure file + handles to be passed to the child process instead of pipes like this: + + ```php + $process = new Process('ping example.com', null, null, array( + array('file', 'nul', 'r'), + $stdout = tmpfile(), + array('file', 'nul', 'w') + )); + $process->start($loop); + + $process->on('exit', function ($exitcode) use ($stdout) { + echo 'exit with ' . $exitcode . PHP_EOL; + + // rewind to start and then read full file (demo only, this is blocking). + // reading from shared file is only safe if you have some synchronization in place + // or after the child process has terminated. + rewind($stdout); + echo stream_get_contents($stdout); + fclose($stdout); + }); + ``` + + Note that this example uses `tmpfile()`/`fopen()` for illustration purposes only. + This should not be used in a truly async program because the filesystem is + inherently blocking and each call could potentially take several seconds. + See also the [Filesystem component](https://github.com/reactphp/filesystem) as an + alternative. + +* If you want to access command output as it happens in a streaming fashion, + you can use redirection to spawn an additional process to forward your + standard I/O streams to a socket and use [custom pipes](#custom-pipes) to + omit any actual standard I/O pipes like this: + + ```php + $server = new React\Socket\Server('127.0.0.1:0', $loop); + $server->on('connection', function (React\Socket\ConnectionInterface $connection) { + $connection->on('data', function ($chunk) { + echo $chunk; + }); + }); + + $command = 'ping example.com | foobar ' . escapeshellarg($server->getAddress()); + $process = new Process($command, null, null, array()); + $process->start($loop); + + $process->on('exit', function ($exitcode) use ($server) { + $server->close(); + echo 'exit with ' . $exitcode . PHP_EOL; + }); + ``` + + Note how this will spawn another fictional `foobar` helper program to consume + the standard output from the actual child process. This is in fact similar + to the above recommendation of using socket connections in the child process, + but in this case does not require modification of the actual child process. + + In this example, the fictional `foobar` helper program can be implemented by + simply consuming all data from standard input and forwarding it to a socket + connection like this: + + ```php + $socket = stream_socket_client($argv[1]); + do { + fwrite($socket, $data = fread(STDIN, 8192)); + } while (isset($data[0])); + ``` + + Accordingly, this example can also be run with plain PHP without having to + rely on any external helper program like this: + + ```php + $code = '$s=stream_socket_client($argv[1]);do{fwrite($s,$d=fread(STDIN, 8192));}while(isset($d[0]));'; + $command = 'ping example.com | php -r ' . escapeshellarg($code) . ' ' . escapeshellarg($server->getAddress()); + $process = new Process($command, null, null, array()); + $process->start($loop); + ``` + + See also [example #23](examples/23-forward-socket.php). + + Note that this is for illustration purposes only and you may want to implement + some proper error checks and/or socket verification in actual production use + if you do not want to risk other processes connecting to the server socket. + In this case, we suggest looking at the excellent + [createprocess-windows](https://github.com/cubiclesoft/createprocess-windows). + +Additionally, note that the [command](#command) given to the `Process` will be +passed to the underlying Windows-API +([`CreateProcess`](https://docs.microsoft.com/en-us/windows/desktop/api/processthreadsapi/nf-processthreadsapi-createprocessa)) +as-is and the process will not be launched in a wrapping shell by default. In +particular, this means that shell built-in functions such as `echo hello` or +`sleep 10` may have to be prefixed with an explicit shell command like this: + +```php +$process = new Process('cmd /c echo hello', null, null, $pipes); +$process->start($loop); +``` ## Install @@ -325,7 +567,7 @@ This will install the latest supported version: ```bash -$ composer require react/child-process:^0.5.2 +$ composer require react/child-process:^0.6.1 ``` See also the [CHANGELOG](CHANGELOG.md) for details about version upgrades. diff -Nru php-react-child-process-0.5.2/src/Process.php php-react-child-process-0.6.1/src/Process.php --- php-react-child-process-0.5.2/src/Process.php 2018-01-18 14:53:06.000000000 +0000 +++ php-react-child-process-0.6.1/src/Process.php 2019-02-15 13:48:16.000000000 +0000 @@ -5,7 +5,9 @@ use Evenement\EventEmitter; use React\EventLoop\LoopInterface; use React\Stream\ReadableResourceStream; +use React\Stream\ReadableStreamInterface; use React\Stream\WritableResourceStream; +use React\Stream\WritableStreamInterface; /** * Process component. @@ -13,20 +15,81 @@ * This class borrows logic from Symfony's Process component for ensuring * compatibility when PHP is compiled with the --enable-sigchild option. * - * @event exit + * This class also implements the `EventEmitterInterface` + * which allows you to react to certain events: + * + * exit event: + * The `exit` event will be emitted whenever the process is no longer running. + * Event listeners will receive the exit code and termination signal as two + * arguments: + * + * ```php + * $process = new Process('sleep 10'); + * $process->start($loop); + * + * $process->on('exit', function ($code, $term) { + * if ($term === null) { + * echo 'exit with code ' . $code . PHP_EOL; + * } else { + * echo 'terminated with signal ' . $term . PHP_EOL; + * } + * }); + * ``` + * + * Note that `$code` is `null` if the process has terminated, but the exit + * code could not be determined (for example + * [sigchild compatibility](#sigchild-compatibility) was disabled). + * Similarly, `$term` is `null` unless the process has terminated in response to + * an uncaught signal sent to it. + * This is not a limitation of this project, but actual how exit codes and signals + * are exposed on POSIX systems, for more details see also + * [here](https://unix.stackexchange.com/questions/99112/default-exit-code-when-process-is-terminated). + * + * It's also worth noting that process termination depends on all file descriptors + * being closed beforehand. + * This means that all [process pipes](#stream-properties) will emit a `close` + * event before the `exit` event and that no more `data` events will arrive after + * the `exit` event. + * Accordingly, if either of these pipes is in a paused state (`pause()` method + * or internally due to a `pipe()` call), this detection may not trigger. */ class Process extends EventEmitter { + /** + * @var WritableStreamInterface|null|ReadableStreamInterface + */ public $stdin; + + /** + * @var ReadableStreamInterface|null|WritableStreamInterface + */ public $stdout; + + /** + * @var ReadableStreamInterface|null|WritableStreamInterface + */ public $stderr; + /** + * Array with all process pipes (once started) + * + * Unless explicitly configured otherwise during construction, the following + * standard I/O pipes will be assigned by default: + * - 0: STDIN (`WritableStreamInterface`) + * - 1: STDOUT (`ReadableStreamInterface`) + * - 2: STDERR (`ReadableStreamInterface`) + * + * @var ReadableStreamInterface|WritableStreamInterface + */ + public $pipes = array(); + private $cmd; private $cwd; private $env; - private $options; + private $fds; + private $enhanceSigchildCompatibility; - private $pipes; + private $sigchildPipe; private $process; private $status; @@ -40,19 +103,15 @@ /** * Constructor. * - * @param string $cmd Command line to run - * @param string $cwd Current working directory or null to inherit - * @param array $env Environment variables or null to inherit - * @param array $options Options for proc_open() - * @throws LogicException On windows or when proc_open() is not installed + * @param string $cmd Command line to run + * @param null|string $cwd Current working directory or null to inherit + * @param null|array $env Environment variables or null to inherit + * @param null|array $fds File descriptors to allocate for this process (or null = default STDIO streams) + * @throws \LogicException On windows or when proc_open() is not installed */ - public function __construct($cmd, $cwd = null, array $env = null, array $options = array()) + public function __construct($cmd, $cwd = null, array $env = null, array $fds = null) { - if (substr(strtolower(PHP_OS), 0, 3) === 'win') { - throw new \LogicException('Windows isn\'t supported due to the blocking nature of STDIN/STDOUT/STDERR pipes.'); - } - - if (!function_exists('proc_open')) { + if (!\function_exists('proc_open')) { throw new \LogicException('The Process class relies on proc_open(), which is not available on your PHP installation.'); } @@ -66,19 +125,35 @@ } } - $this->options = $options; - $this->enhanceSigchildCompatibility = $this->isSigchildEnabled(); + if ($fds === null) { + $fds = array( + array('pipe', 'r'), // stdin + array('pipe', 'w'), // stdout + array('pipe', 'w'), // stderr + ); + } + + if (\DIRECTORY_SEPARATOR === '\\') { + foreach ($fds as $fd) { + if (isset($fd[0]) && $fd[0] === 'pipe') { + throw new \LogicException('Process pipes are not supported on Windows due to their blocking nature on Windows'); + } + } + } + + $this->fds = $fds; + $this->enhanceSigchildCompatibility = self::isSigchildEnabled(); } /** * Start the process. * - * After the process is started, the standard IO streams will be constructed - * and available via public properties. STDIN will be paused upon creation. + * After the process is started, the standard I/O streams will be constructed + * and available via public properties. * * @param LoopInterface $loop Loop interface for stream construction * @param float $interval Interval to periodically monitor process state (seconds) - * @throws RuntimeException If the process is already running or fails to start + * @throws \RuntimeException If the process is already running or fails to start */ public function start(LoopInterface $loop, $interval = 0.1) { @@ -87,31 +162,47 @@ } $cmd = $this->cmd; - $fdSpec = array( - array('pipe', 'r'), // stdin - array('pipe', 'w'), // stdout - array('pipe', 'w'), // stderr - ); + $fdSpec = $this->fds; + $sigchild = null; // Read exit code through fourth pipe to work around --enable-sigchild - if ($this->isSigchildEnabled() && $this->enhanceSigchildCompatibility) { + if ($this->enhanceSigchildCompatibility) { $fdSpec[] = array('pipe', 'w'); - $cmd = sprintf('(%s) 3>/dev/null; code=$?; echo $code >&3; exit $code', $cmd); - } + \end($fdSpec); + $sigchild = \key($fdSpec); - $this->process = proc_open($cmd, $fdSpec, $this->pipes, $this->cwd, $this->env, $this->options); + // make sure this is fourth or higher (do not mess with STDIO) + if ($sigchild < 3) { + $fdSpec[3] = $fdSpec[$sigchild]; + unset($fdSpec[$sigchild]); + $sigchild = 3; + } - if (!is_resource($this->process)) { - throw new \RuntimeException('Unable to launch a new process.'); + $cmd = \sprintf('(%s) ' . $sigchild . '>/dev/null; code=$?; echo $code >&' . $sigchild . '; exit $code', $cmd); } - $closeCount = 0; + // on Windows, we do not launch the given command line in a shell (cmd.exe) by default and omit any error dialogs + // the cmd.exe shell can explicitly be given as part of the command as detailed in both documentation and tests + $options = array(); + if (\DIRECTORY_SEPARATOR === '\\') { + $options['bypass_shell'] = true; + $options['suppress_errors'] = true; + } + + $this->process = @\proc_open($cmd, $fdSpec, $pipes, $this->cwd, $this->env, $options); + if (!\is_resource($this->process)) { + $error = \error_get_last(); + throw new \RuntimeException('Unable to launch a new process: ' . $error['message']); + } + + // count open process pipes and await close event for each to drain buffers before detecting exit $that = $this; + $closeCount = 0; $streamCloseHandler = function () use (&$closeCount, $loop, $interval, $that) { - $closeCount++; + $closeCount--; - if ($closeCount < 2) { + if ($closeCount > 0) { return; } @@ -132,11 +223,30 @@ }); }; - $this->stdin = new WritableResourceStream($this->pipes[0], $loop); - $this->stdout = new ReadableResourceStream($this->pipes[1], $loop); - $this->stdout->on('close', $streamCloseHandler); - $this->stderr = new ReadableResourceStream($this->pipes[2], $loop); - $this->stderr->on('close', $streamCloseHandler); + if ($sigchild !== null) { + $this->sigchildPipe = $pipes[$sigchild]; + unset($pipes[$sigchild]); + } + + foreach ($pipes as $n => $fd) { + if (\strpos($this->fds[$n][1], 'w') === false) { + $stream = new WritableResourceStream($fd, $loop); + } else { + $stream = new ReadableResourceStream($fd, $loop); + $stream->on('close', $streamCloseHandler); + $closeCount++; + } + $this->pipes[$n] = $stream; + } + + $this->stdin = isset($this->pipes[0]) ? $this->pipes[0] : null; + $this->stdout = isset($this->pipes[1]) ? $this->pipes[1] : null; + $this->stderr = isset($this->pipes[2]) ? $this->pipes[2] : null; + + // immediately start checking for process exit when started without any I/O pipes + if (!$closeCount) { + $streamCloseHandler(); + } } /** @@ -151,16 +261,16 @@ return; } - $this->stdin->close(); - $this->stdout->close(); - $this->stderr->close(); + foreach ($this->pipes as $pipe) { + $pipe->close(); + } - if ($this->isSigchildEnabled() && $this->enhanceSigchildCompatibility) { + if ($this->enhanceSigchildCompatibility) { $this->pollExitCodePipe(); $this->closeExitCodePipe(); } - $exitCode = proc_close($this->process); + $exitCode = \proc_close($this->process); $this->process = null; if ($this->exitCode === null && $exitCode !== -1) { @@ -181,7 +291,7 @@ * Terminate the process with an optional signal. * * @param int $signal Optional signal (default: SIGTERM) - * @return boolean Whether the signal was sent successfully + * @return bool Whether the signal was sent successfully */ public function terminate($signal = null) { @@ -190,10 +300,10 @@ } if ($signal !== null) { - return proc_terminate($this->process, $signal); + return \proc_terminate($this->process, $signal); } - return proc_terminate($this->process); + return \proc_terminate($this->process); } /** @@ -207,38 +317,6 @@ } /** - * Return whether sigchild compatibility is enabled. - * - * @return boolean - */ - public final function getEnhanceSigchildCompatibility() - { - return $this->enhanceSigchildCompatibility; - } - - /** - * Enable or disable sigchild compatibility mode. - * - * Sigchild compatibility mode is required to get the exit code and - * determine the success of a process when PHP has been compiled with - * the --enable-sigchild option. - * - * @param boolean $enhance - * @return self - * @throws RuntimeException If the process is already running - */ - public final function setEnhanceSigchildCompatibility($enhance) - { - if ($this->isRunning()) { - throw new \RuntimeException('Process is already running'); - } - - $this->enhanceSigchildCompatibility = (bool) $enhance; - - return $this; - } - - /** * Get the exit code returned by the process. * * This value is only meaningful if isRunning() has returned false. Null @@ -295,7 +373,7 @@ /** * Return whether the process is still running. * - * @return boolean + * @return bool */ public function isRunning() { @@ -311,7 +389,7 @@ /** * Return whether the process has been stopped by a signal. * - * @return boolean + * @return bool */ public function isStopped() { @@ -323,7 +401,7 @@ /** * Return whether the process has been terminated by an uncaught signal. * - * @return boolean + * @return bool */ public function isTerminated() { @@ -344,10 +422,25 @@ return self::$sigchild; } - ob_start(); - phpinfo(INFO_GENERAL); + \ob_start(); + \phpinfo(INFO_GENERAL); + + return self::$sigchild = false !== \strpos(\ob_get_clean(), '--enable-sigchild'); + } - return self::$sigchild = false !== strpos(ob_get_clean(), '--enable-sigchild'); + /** + * Enable or disable sigchild compatibility mode. + * + * Sigchild compatibility mode is required to get the exit code and + * determine the success of a process when PHP has been compiled with + * the --enable-sigchild option. + * + * @param bool $sigchild + * @return void + */ + public final static function setSigchildEnabled($sigchild) + { + self::$sigchild = (bool) $sigchild; } /** @@ -357,22 +450,22 @@ */ private function pollExitCodePipe() { - if ( ! isset($this->pipes[3])) { + if ($this->sigchildPipe === null) { return; } - $r = array($this->pipes[3]); + $r = array($this->sigchildPipe); $w = $e = null; - $n = @stream_select($r, $w, $e, 0); + $n = @\stream_select($r, $w, $e, 0); if (1 !== $n) { return; } - $data = fread($r[0], 8192); + $data = \fread($r[0], 8192); - if (strlen($data) > 0) { + if (\strlen($data) > 0) { $this->fallbackExitCode = (int) $data; } } @@ -384,12 +477,12 @@ */ private function closeExitCodePipe() { - if ( ! isset($this->pipes[3])) { + if ($this->sigchildPipe === null) { return; } - fclose($this->pipes[3]); - unset($this->pipes[3]); + \fclose($this->sigchildPipe); + $this->sigchildPipe = null; } /** @@ -431,7 +524,7 @@ return; } - $this->status = proc_get_status($this->process); + $this->status = \proc_get_status($this->process); if ($this->status === false) { throw new \UnexpectedValueException('proc_get_status() failed'); diff -Nru php-react-child-process-0.5.2/tests/AbstractProcessTest.php php-react-child-process-0.6.1/tests/AbstractProcessTest.php --- php-react-child-process-0.5.2/tests/AbstractProcessTest.php 2018-01-18 14:53:06.000000000 +0000 +++ php-react-child-process-0.6.1/tests/AbstractProcessTest.php 2019-02-15 13:48:16.000000000 +0000 @@ -11,38 +11,137 @@ { abstract public function createLoop(); - public function testGetEnhanceSigchildCompatibility() + public function testGetCommand() + { + $process = new Process('echo foo', null, null, array()); + + $this->assertSame('echo foo', $process->getCommand()); + } + + public function testPipesWillBeUnsetBeforeStarting() + { + if (DIRECTORY_SEPARATOR === '\\') { + $this->markTestSkipped('Process pipes not supported on Windows'); + } + + $process = new Process('echo foo'); + + $this->assertNull($process->stdin); + $this->assertNull($process->stdout); + $this->assertNull($process->stderr); + $this->assertEquals(array(), $process->pipes); + } + + /** + * @depends testPipesWillBeUnsetBeforeStarting + */ + public function testStartWillAssignPipes() { $process = new Process('echo foo'); + $process->start($this->createLoop()); + + $this->assertInstanceOf('React\Stream\WritableStreamInterface', $process->stdin); + $this->assertInstanceOf('React\Stream\ReadableStreamInterface', $process->stdout); + $this->assertInstanceOf('React\Stream\ReadableStreamInterface', $process->stderr); + $this->assertCount(3, $process->pipes); + $this->assertSame($process->stdin, $process->pipes[0]); + $this->assertSame($process->stdout, $process->pipes[1]); + $this->assertSame($process->stderr, $process->pipes[2]); + } + + public function testStartWithoutAnyPipesWillNotAssignPipes() + { + if (DIRECTORY_SEPARATOR === '\\') { + $process = new Process('cmd /c exit 0', null, null, array()); + } else { + $process = new Process('exit 0', null, null, array()); + } + $process->start($this->createLoop()); + + $this->assertNull($process->stdin); + $this->assertNull($process->stdout); + $this->assertNull($process->stderr); + $this->assertEquals(array(), $process->pipes); + } + + public function testStartWithCustomPipesWillAssignPipes() + { + if (DIRECTORY_SEPARATOR === '\\') { + $this->markTestSkipped('Process pipes not supported on Windows'); + } - $this->assertSame($process, $process->setEnhanceSigchildCompatibility(true)); - $this->assertTrue($process->getEnhanceSigchildCompatibility()); + $process = new Process('exit 0', null, null, array( + 0 => array('pipe', 'w'), + 3 => array('pipe', 'r') + )); + $process->start($this->createLoop()); - $this->assertSame($process, $process->setEnhanceSigchildCompatibility(false)); - $this->assertFalse($process->getEnhanceSigchildCompatibility()); + $this->assertInstanceOf('React\Stream\ReadableStreamInterface', $process->stdin); + $this->assertNull($process->stdout); + $this->assertNull($process->stderr); + $this->assertCount(2, $process->pipes); + $this->assertSame($process->stdin, $process->pipes[0]); + $this->assertInstanceOf('React\Stream\WritableStreamInterface', $process->pipes[3]); } /** * @expectedException RuntimeException + * @expectedExceptionMessage No such file or directory */ - public function testSetEnhanceSigchildCompatibilityCannotBeCalledIfProcessIsRunning() + public function testStartWithInvalidFileDescriptorPathWillThrow() { - $process = new Process('sleep 1'); + $fds = array( + 4 => array('file', '/dev/does-not-exist', 'r') + ); + $process = new Process('exit 0', null, null, $fds); $process->start($this->createLoop()); - $process->setEnhanceSigchildCompatibility(false); } - public function testGetCommand() + public function testStartWithExcessiveNumberOfFileDescriptorsWillThrow() { - $process = new Process('echo foo'); + if (PHP_VERSION_ID < 70000) { + $this->markTestSkipped('PHP 7+ only, causes memory overflow on legacy PHP 5'); + } - $this->assertSame('echo foo', $process->getCommand()); + $ulimit = exec('ulimit -n 2>&1'); + if ($ulimit < 1) { + $this->markTestSkipped('Unable to determine limit of open files (ulimit not available?)'); + } + + $loop = $this->createLoop(); + + // create 70% (usually ~700) dummy file handles in this parent dummy + $limit = (int)($ulimit * 0.7); + $fds = array(); + for ($i = 0; $i < $limit; ++$i) { + $fds[$i] = fopen('/dev/null', 'r'); + } + + // try to create child process with another ~700 dummy file handles + $new = array_fill(0, $limit, array('file', '/dev/null', 'r')); + $process = new Process('ping example.com', null, null, $new); + + try { + $process->start($loop); + + $this->fail('Did not expect to reach this point'); + } catch (\RuntimeException $e) { + // clear dummy files handles to make some room again (avoid fatal errors for autoloader) + $fds = array(); + + $this->assertContains('Too many open files', $e->getMessage()); + } } public function testIsRunning() { - $process = new Process('sleep 1'); + if (DIRECTORY_SEPARATOR === '\\') { + // Windows doesn't have a sleep command and also does not support process pipes + $process = new Process($this->getPhpBinary() . ' -r ' . escapeshellarg('sleep(1);'), null, null, array()); + } else { + $process = new Process('sleep 1'); + } $this->assertFalse($process->isRunning()); $process->start($this->createLoop()); @@ -67,8 +166,30 @@ $this->assertNull($process->getTermSignal()); } + public function testCommandWithEnhancedSigchildCompatibilityReceivesExitCode() + { + if (DIRECTORY_SEPARATOR === '\\') { + $this->markTestSkipped('Process pipes not supported on Windows'); + } + + $loop = $this->createLoop(); + $old = Process::isSigchildEnabled(); + Process::setSigchildEnabled(true); + $process = new Process('echo foo'); + $process->start($loop); + Process::setSigchildEnabled($old); + + $loop->run(); + + $this->assertEquals(0, $process->getExitCode()); + } + public function testReceivesProcessStdoutFromEcho() { + if (DIRECTORY_SEPARATOR === '\\') { + $this->markTestSkipped('Process pipes not supported on Windows'); + } + $cmd = 'echo test'; $loop = $this->createLoop(); @@ -85,8 +206,106 @@ $this->assertEquals('test', rtrim($buffer)); } + public function testReceivesProcessOutputFromStdoutRedirectedToFile() + { + $tmp = tmpfile(); + + if (DIRECTORY_SEPARATOR === '\\') { + $cmd = 'cmd /c echo test'; + } else { + $cmd = 'echo test'; + } + + $loop = $this->createLoop(); + $process = new Process($cmd, null, null, array(1 => $tmp)); + $process->start($loop); + + $loop->run(); + + rewind($tmp); + $this->assertEquals('test', rtrim(stream_get_contents($tmp))); + } + + public function testReceivesProcessOutputFromTwoCommandsChainedStdoutRedirectedToFile() + { + $tmp = tmpfile(); + + if (DIRECTORY_SEPARATOR === '\\') { + // omit whitespace before "&&" and quotation marks as Windows will actually echo this otherwise + $cmd = 'cmd /c echo hello&& cmd /c echo world'; + } else { + $cmd = 'echo "hello" && echo "world"'; + } + + $loop = $this->createLoop(); + $process = new Process($cmd, null, null, array(1 => $tmp)); + $process->start($loop); + + $loop->run(); + + rewind($tmp); + $this->assertEquals("hello\nworld", str_replace("\r\n", "\n", rtrim(stream_get_contents($tmp)))); + } + + public function testReceivesProcessOutputFromStdoutAttachedToSocket() + { + if (DIRECTORY_SEPARATOR === '\\') { + $this->markTestSkipped('Sockets as STDIO handles not supported on Windows'); + } + + // create TCP/IP server on random port and create a client connection + $server = stream_socket_server('tcp://127.0.0.1:0'); + $client = stream_socket_client(stream_socket_get_name($server, false)); + $peer = stream_socket_accept($server, 0); + fclose($server); + + $cmd = 'echo test'; + + $loop = $this->createLoop(); + + // spawn child process with $client socket as STDOUT, close local reference afterwards + $process = new Process($cmd, null, null, array(1 => $client)); + $process->start($loop); + fclose($client); + + $loop->run(); + + $this->assertEquals('test', rtrim(stream_get_contents($peer))); + } + + public function testReceivesProcessOutputFromStdoutRedirectedToSocketProcess() + { + // create TCP/IP server on random port and wait for client connection + $server = stream_socket_server('tcp://127.0.0.1:0'); + + if (DIRECTORY_SEPARATOR === '\\') { + $cmd = 'cmd /c echo test'; + } else { + $cmd = 'exec echo test'; + } + + $code = '$s=stream_socket_client($argv[1]);do{$d=fread(STDIN,8192);fwrite($s,$d);}while(!feof(STDIN));fclose($s);'; + $cmd .= ' | ' . $this->getPhpBinary() . ' -r ' . escapeshellarg($code) . ' ' . escapeshellarg(stream_socket_get_name($server, false)); + + $loop = $this->createLoop(); + + // spawn child process without any STDIO streams + $process = new Process($cmd, null, null, array()); + $process->start($loop); + + $peer = stream_socket_accept($server, 10); + + $loop->run(); + + $this->assertEquals('test', rtrim(stream_get_contents($peer))); + } + public function testReceivesProcessStdoutFromDd() { + if (DIRECTORY_SEPARATOR === '\\') { + $this->markTestSkipped('Process pipes not supported on Windows'); + } + if (!file_exists('/dev/zero')) { $this->markTestSkipped('Unable to read from /dev/zero, Windows?'); } @@ -109,6 +328,10 @@ public function testProcessPidNotSameDueToShellWrapper() { + if (DIRECTORY_SEPARATOR === '\\') { + $this->markTestSkipped('Process pipes not supported on Windows'); + } + $cmd = $this->getPhpBinary() . ' -r ' . escapeshellarg('echo getmypid();'); $loop = $this->createLoop(); @@ -129,6 +352,10 @@ public function testProcessPidSameWithExec() { + if (DIRECTORY_SEPARATOR === '\\') { + $this->markTestSkipped('Process pipes not supported on Windows'); + } + $cmd = 'exec ' . $this->getPhpBinary() . ' -r ' . escapeshellarg('echo getmypid();'); $loop = $this->createLoop(); @@ -148,6 +375,10 @@ public function testProcessWithDefaultCwdAndEnv() { + if (DIRECTORY_SEPARATOR === '\\') { + $this->markTestSkipped('Process pipes not supported on Windows'); + } + $cmd = $this->getPhpBinary() . ' -r ' . escapeshellarg('echo getcwd(), PHP_EOL, count($_SERVER), PHP_EOL;'); $loop = $this->createLoop(); @@ -174,6 +405,10 @@ public function testProcessWithCwd() { + if (DIRECTORY_SEPARATOR === '\\') { + $this->markTestSkipped('Process pipes not supported on Windows'); + } + $cmd = $this->getPhpBinary() . ' -r ' . escapeshellarg('echo getcwd(), PHP_EOL;'); $loop = $this->createLoop(); @@ -193,6 +428,10 @@ public function testProcessWithEnv() { + if (DIRECTORY_SEPARATOR === '\\') { + $this->markTestSkipped('Process pipes not supported on Windows'); + } + if (getenv('TRAVIS')) { $this->markTestSkipped('Cannot execute PHP processes with custom environments on Travis CI.'); } @@ -216,6 +455,10 @@ public function testStartAndAllowProcessToExitSuccessfullyUsingEventLoop() { + if (DIRECTORY_SEPARATOR === '\\') { + $this->markTestSkipped('Process pipes not supported on Windows'); + } + $loop = $this->createLoop(); $process = new Process('exit 0'); @@ -245,6 +488,10 @@ public function testProcessWillExitFasterThanExitInterval() { + if (DIRECTORY_SEPARATOR === '\\') { + $this->markTestSkipped('Process pipes not supported on Windows'); + } + $loop = $this->createLoop(); $process = new Process('echo hi'); $process->start($loop, 2); @@ -258,6 +505,10 @@ public function testDetectsClosingStdoutWithoutHavingToWaitForExit() { + if (DIRECTORY_SEPARATOR === '\\') { + $this->markTestSkipped('Process pipes not supported on Windows'); + } + $cmd = 'exec ' . $this->getPhpBinary() . ' -r ' . escapeshellarg('fclose(STDOUT); sleep(1);'); $loop = $this->createLoop(); @@ -265,12 +516,13 @@ $process->start($loop); $closed = false; - $process->stdout->on('close', function () use (&$closed) { + $process->stdout->on('close', function () use (&$closed, $loop) { $closed = true; + $loop->stop(); }); - // run loop for 0.1s only - $loop->addTimer(0.1, function () use ($loop) { + // run loop for maximum of 0.5s only + $loop->addTimer(0.5, function () use ($loop) { $loop->stop(); }); $loop->run(); @@ -280,6 +532,10 @@ public function testKeepsRunningEvenWhenAllStdioPipesHaveBeenClosed() { + if (DIRECTORY_SEPARATOR === '\\') { + $this->markTestSkipped('Process pipes not supported on Windows'); + } + $cmd = 'exec ' . $this->getPhpBinary() . ' -r ' . escapeshellarg('fclose(STDIN);fclose(STDOUT);fclose(STDERR);sleep(1);'); $loop = $this->createLoop(); @@ -287,15 +543,21 @@ $process->start($loop); $closed = 0; - $process->stdout->on('close', function () use (&$closed) { + $process->stdout->on('close', function () use (&$closed, $loop) { ++$closed; + if ($closed === 2) { + $loop->stop(); + } }); - $process->stderr->on('close', function () use (&$closed) { + $process->stderr->on('close', function () use (&$closed, $loop) { ++$closed; + if ($closed === 2) { + $loop->stop(); + } }); - // run loop for 0.1s only - $loop->addTimer(0.1, function () use ($loop) { + // run loop for maximum 0.5s only + $loop->addTimer(0.5, function () use ($loop) { $loop->stop(); }); $loop->run(); @@ -306,6 +568,10 @@ public function testDetectsClosingProcessEvenWhenAllStdioPipesHaveBeenClosed() { + if (DIRECTORY_SEPARATOR === '\\') { + $this->markTestSkipped('Process pipes not supported on Windows'); + } + $cmd = 'exec ' . $this->getPhpBinary() . ' -r ' . escapeshellarg('fclose(STDIN);fclose(STDOUT);fclose(STDERR);usleep(10000);'); $loop = $this->createLoop(); @@ -316,11 +582,36 @@ $loop->run(); $time = microtime(true) - $time; + $this->assertLessThan(0.5, $time); + $this->assertSame(0, $process->getExitCode()); + } + + public function testDetectsClosingProcessEvenWhenStartedWithoutPipes() + { + $loop = $this->createLoop(); + + if (DIRECTORY_SEPARATOR === '\\') { + $process = new Process('cmd /c exit 0', null, null, array()); + } else { + $process = new Process('exit 0', null, null, array()); + } + + $process->start($loop, 0.001); + + $time = microtime(true); + $loop->run(); + $time = microtime(true) - $time; + $this->assertLessThan(0.1, $time); + $this->assertSame(0, $process->getExitCode()); } public function testStartInvalidProcess() { + if (DIRECTORY_SEPARATOR === '\\') { + $this->markTestSkipped('Process pipes not supported on Windows'); + } + $cmd = tempnam(sys_get_temp_dir(), 'react'); $loop = $this->createLoop(); @@ -345,7 +636,13 @@ */ public function testStartAlreadyRunningProcess() { - $process = new Process('sleep 1'); + if (DIRECTORY_SEPARATOR === '\\') { + // Windows doesn't have a sleep command and also does not support process pipes + $process = new Process($this->getPhpBinary() . ' -r ' . escapeshellarg('sleep(1);'), null, null, array()); + } else { + $process = new Process('sleep 1'); + } + //var_dump($process); $process->start($this->createLoop()); $process->start($this->createLoop()); @@ -353,16 +650,27 @@ public function testTerminateProcesWithoutStartingReturnsFalse() { - $process = new Process('sleep 1'); + if (DIRECTORY_SEPARATOR === '\\') { + // Windows doesn't have a sleep command and also does not support process pipes + $process = new Process($this->getPhpBinary() . ' -r ' . escapeshellarg('sleep(1);'), null, null, array()); + } else { + $process = new Process('sleep 1'); + } $this->assertFalse($process->terminate()); } public function testTerminateWillExit() { + if (DIRECTORY_SEPARATOR === '\\') { + // Windows doesn't have a sleep command and also does not support process pipes + $process = new Process($this->getPhpBinary() . ' -r ' . escapeshellarg('sleep(10);'), null, null, array()); + } else { + $process = new Process('sleep 10'); + } + $loop = $this->createloop(); - $process = new Process('sleep 10'); $process->start($loop); $called = false; @@ -370,9 +678,9 @@ $called = true; }); - $process->stdin->close(); - $process->stdout->close(); - $process->stderr->close(); + foreach ($process->pipes as $pipe) { + $pipe->close(); + } $process->terminate(); $loop->run(); @@ -382,7 +690,7 @@ public function testTerminateWithDefaultTermSignalUsingEventLoop() { - if (defined('PHP_WINDOWS_VERSION_BUILD')) { + if (DIRECTORY_SEPARATOR === '\\') { $this->markTestSkipped('Windows does not report signals via proc_get_status()'); } @@ -420,7 +728,7 @@ public function testTerminateWithStopAndContinueSignalsUsingEventLoop() { - if (defined('PHP_WINDOWS_VERSION_BUILD')) { + if (DIRECTORY_SEPARATOR === '\\') { $this->markTestSkipped('Windows does not report signals via proc_get_status()'); } @@ -470,7 +778,12 @@ $this->assertFalse($process->isTerminated()); } - public function testIssue18() { + public function testIssue18() + { + if (DIRECTORY_SEPARATOR === '\\') { + $this->markTestSkipped('Process pipes not supported on Windows'); + } + $loop = $this->createLoop(); $testString = 'x'; @@ -520,7 +833,7 @@ * Execute a callback at regular intervals until it returns successfully or * a timeout is reached. * - * @param Closure $callback Callback with one or more assertions + * @param \Closure $callback Callback with one or more assertions * @param integer $timeout Time limit for callback to succeed (milliseconds) * @param integer $interval Interval for retrying the callback (milliseconds) * @throws PHPUnit_Framework_ExpectationFailedException Last exception raised by the callback @@ -549,6 +862,11 @@ } } + /** + * Returns the path to the PHP binary. This is already escapescaped via `escapeshellarg()`. + * + * @return string + */ private function getPhpBinary() { $runtime = new Runtime(); diff -Nru php-react-child-process-0.5.2/.travis.yml php-react-child-process-0.6.1/.travis.yml --- php-react-child-process-0.5.2/.travis.yml 2018-01-18 14:53:06.000000000 +0000 +++ php-react-child-process-0.6.1/.travis.yml 2019-02-15 13:48:16.000000000 +0000 @@ -7,7 +7,9 @@ - 5.6 - 7.0 - 7.1 - - hhvm # ignore errors, see below + - 7.2 + - 7.3 +# - hhvm # requires legacy phpunit & ignore errors, see below # lock distro so new future defaults will not break the build dist: trusty @@ -16,14 +18,24 @@ include: - php: 5.3 dist: precise + - php: hhvm + install: composer require phpunit/phpunit:^5 --dev --no-interaction + - name: "Windows" + os: windows + language: shell # no built-in php support + before_install: + - choco install php + - choco install composer + - export PATH="$(powershell -Command '("Process", "Machine" | % { [Environment]::GetEnvironmentVariable("PATH", $_) -Split ";" -Replace "\\$", "" } | Select -Unique | % { cygpath $_ }) -Join ":"')" allow_failures: - php: hhvm + - os: windows sudo: false install: - composer install --no-interaction - + script: - vendor/bin/phpunit --coverage-text - php examples/13-benchmark-throughput.php