PK 5dAV›Ñ>_ _ phpunit.xml.distnu W+A„¶
test
lib
PK 5dAVTÌëuM M lib/ProcessException.phpnu W+A„¶ command = $command;
$this->cwd = $cwd ?? "";
foreach ($env as $key => $value) {
if (\is_array($value)) {
throw new \Error("\$env cannot accept array values");
}
$this->env[(string) $key] = (string) $value;
}
$this->options = $options;
}
/**
* Stops the process if it is still running.
*/
public function __destruct() {
if (\getmypid() === $this->oid) {
$this->kill(); // Will only terminate if the process is still running.
}
if ($this->watcher !== null) {
Loop::cancel($this->watcher);
}
if ($this->stdin && \is_resource($resource = $this->stdin->getResource())) {
\fclose($resource);
}
if ($this->stdout && \is_resource($resource = $this->stdout->getResource())) {
\fclose($resource);
}
if ($this->stderr && \is_resource($resource = $this->stderr->getResource())) {
\fclose($resource);
}
if (\is_resource($this->process)) {
\proc_close($this->process);
}
}
/**
* Resets process values.
*/
public function __clone() {
$this->process = null;
$this->deferred = null;
$this->watcher = null;
$this->pid = 0;
$this->oid = 0;
$this->stdin = null;
$this->stdout = null;
$this->stderr = null;
$this->running = false;
}
/**
* @throws \Amp\Process\ProcessException If starting the process fails.
* @throws \Amp\Process\StatusError If the process is already running.
*/
public function start() {
if ($this->deferred !== null) {
throw new StatusError("The process has already been started");
}
$this->deferred = $deferred = new Deferred;
$fd = [
["pipe", "r"], // stdin
["pipe", "w"], // stdout
["pipe", "w"], // stderr
["pipe", "w"], // exit code pipe
];
if (self::$onWindows) {
$command = $this->command;
} else {
$command = \sprintf(
'{ (%s) <&3 3<&- 3>/dev/null & } 3<&0;' .
'pid=$!; echo $pid >&3; wait $pid; RC=$?; echo $RC >&3; exit $RC',
$this->command
);
}
$this->process = @\proc_open($command, $fd, $pipes, $this->cwd ?: null, $this->env ?: null, $this->options);
if (!\is_resource($this->process)) {
$message = "Could not start process";
if ($error = \error_get_last()) {
$message .= \sprintf(" Errno: %d; %s", $error["type"], $error["message"]);
}
$deferred->fail(new ProcessException($message));
return;
}
$this->oid = \getmypid();
$status = \proc_get_status($this->process);
if (!$status) {
\proc_close($this->process);
$this->process = null;
$deferred->fail(new ProcessException("Could not get process status"));
return;
}
if (self::$onWindows) {
$this->pid = $status["pid"];
$exitcode = $status["exitcode"];
} else {
// This blocking read will only block until the process scheduled, generally a few microseconds.
$pid = \rtrim(@\fgets($pipes[3]));
$exitcode = -1;
if (!$pid || !\is_numeric($pid)) {
$deferred->fail(new ProcessException("Could not determine PID"));
return;
}
$this->pid = (int) $pid;
}
$this->stdin = new ResourceOutputStream($pipes[0]);
$this->stdout = new ResourceInputStream($pipes[1]);
$this->stderr = new ResourceInputStream($pipes[2]);
\stream_set_blocking($pipes[3], false);
$this->running = true;
$process = &$this->process;
$running = &$this->running;
$this->watcher = Loop::onReadable($pipes[3], static function ($watcher, $resource) use (
&$process, &$running, $exitcode, $deferred
) {
Loop::cancel($watcher);
$running = false;
try {
try {
if (self::$onWindows) {
// Avoid a generator on Unix
$code = call(function () use ($exitcode, $process) {
$status = \proc_get_status($process);
while ($status["running"]) {
yield new Delayed(10);
$status = \proc_get_status($process);
}
$code = $exitcode !== -1 ? $exitcode : $status["exitcode"];
return (int) $code;
});
} elseif (!\is_resource($resource) || \feof($resource)) {
throw new ProcessException("Process ended unexpectedly");
} else {
$code = (int) \rtrim(@\stream_get_contents($resource));
}
} finally {
if (\is_resource($resource)) {
\fclose($resource);
}
}
} catch (\Throwable $exception) {
$deferred->fail($exception);
return;
}
$deferred->resolve($code);
});
Loop::unreference($this->watcher);
}
/**
* @return \Amp\Promise Succeeds with exit code of the process or fails if the process is killed.
*/
public function join(): Promise {
if ($this->deferred === null) {
throw new StatusError("The process is not running");
}
if ($this->watcher !== null && $this->running) {
Loop::reference($this->watcher);
}
return $this->deferred->promise();
}
/**
* {@inheritdoc}
*/
public function kill() {
if ($this->running && \is_resource($this->process)) {
$this->running = false;
// Forcefully kill the process using SIGKILL.
\proc_terminate($this->process, 9);
Loop::cancel($this->watcher);
$this->deferred->fail(new ProcessException("The process was killed"));
}
}
/**
* Sends the given signal to the process.
*
* @param int $signo Signal number to send to process.
*
* @throws \Amp\Process\StatusError If the process is not running.
*/
public function signal(int $signo) {
if (!$this->isRunning()) {
throw new StatusError("The process is not running");
}
\proc_terminate($this->process, $signo);
}
/**
* Returns the PID of the child process. Value is only meaningful if PHP was not compiled with --enable-sigchild.
*
* @return int
*
* @throws \Amp\Process\StatusError
*/
public function getPid(): int {
if ($this->pid === 0) {
throw new StatusError("The process has not been started");
}
return $this->pid;
}
/**
* Returns the command to execute.
*
* @return string The command to execute.
*/
public function getCommand(): string {
return $this->command;
}
/**
* Gets the current working directory.
*
* @return string The current working directory an empty string if inherited from the current PHP process.
*/
public function getWorkingDirectory(): string {
if ($this->cwd === "") {
return \getcwd() ?: "";
}
return $this->cwd;
}
/**
* Gets the environment variables array.
*
* @return string[] Array of environment variables.
*/
public function getEnv(): array {
return $this->env;
}
/**
* Gets the options to pass to proc_open().
*
* @return mixed[] Array of options.
*/
public function getOptions(): array {
return $this->options;
}
/**
* Determines if the process is still running.
*
* @return bool
*/
public function isRunning(): bool {
return $this->running;
}
/**
* Gets the process input stream (STDIN).
*
* @return \Amp\ByteStream\OutputStream
*
* @throws \Amp\Process\StatusError If the process is not running.
*/
public function getStdin(): OutputStream {
if ($this->stdin === null) {
throw new StatusError("The process has not been started");
}
return $this->stdin;
}
/**
* Gets the process output stream (STDOUT).
*
* @return \Amp\ByteStream\InputStream
*
* @throws \Amp\Process\StatusError If the process is not running.
*/
public function getStdout(): InputStream {
if ($this->stdout === null) {
throw new StatusError("The process has not been started");
}
return $this->stdout;
}
/**
* Gets the process error stream (STDERR).
*
* @return \Amp\ByteStream\InputStream
*
* @throws \Amp\Process\StatusError If the process is not running.
*/
public function getStderr(): InputStream {
if ($this->stderr === null) {
throw new StatusError("The process has not been started");
}
return $this->stderr;
}
}
PK 5dAVÛ4)u u LICENSEnu W+A„¶ The MIT License (MIT)
Copyright (c) 2017 amphp
Contributions are licensed subject to the rules in CONTRIBUTORS.md.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
PK 5dAV»88E§ § .travis.ymlnu W+A„¶ sudo: false
language: php
php:
- 7.0
- 7.1
- nightly
matrix:
allow_failures:
- php: nightly
fast_finish: true
install:
# --ignore-platform-reqs, because https://github.com/FriendsOfPHP/PHP-CS-Fixer/pull/2722
- composer update -n --prefer-dist --ignore-platform-reqs
- composer require satooshi/php-coveralls dev-master --ignore-platform-reqs
script:
- phpdbg -qrr vendor/bin/phpunit --coverage-text --coverage-clover build/logs/clover.xml
- php vendor/bin/fqn-check lib
- PHP_CS_FIXER_IGNORE_ENV=1 php vendor/bin/php-cs-fixer --diff --dry-run -v fix
after_script:
- php vendor/bin/coveralls -v
cache:
directories:
- $HOME/.composer/cache
PK 5dAVç¥s s .php_csnu W+A„¶ setRiskyAllowed(true)
->setRules([
"@PSR1" => true,
"@PSR2" => true,
"braces" => [
"allow_single_line_closure" => true,
"position_after_functions_and_oop_constructs" => "same",
],
"array_syntax" => ["syntax" => "short"],
"cast_spaces" => true,
"combine_consecutive_unsets" => true,
"function_to_constant" => true,
"no_multiline_whitespace_before_semicolons" => true,
"no_unused_imports" => true,
"no_useless_else" => true,
"no_useless_return" => true,
"no_whitespace_before_comma_in_array" => true,
"no_whitespace_in_blank_line" => true,
"non_printable_character" => true,
"normalize_index_brace" => true,
"ordered_imports" => true,
"php_unit_construct" => true,
"php_unit_dedicate_assert" => true,
"php_unit_fqcn_annotation" => true,
"phpdoc_summary" => true,
"phpdoc_types" => true,
"psr4" => true,
"return_type_declaration" => ["space_before" => "none"],
"short_scalar_cast" => true,
"single_blank_line_before_namespace" => true,
])
->setFinder(
PhpCsFixer\Finder::create()
->in(__DIR__ . "/examples")
->in(__DIR__ . "/lib")
->in(__DIR__ . "/test")
);
PK 5dAVmºámà à
composer.jsonnu W+A„¶ {
"name": "amphp/process",
"homepage": "https://github.com/amphp/process",
"description": "Asynchronous process manager",
"require": {
"amphp/amp": "^2",
"amphp/byte-stream": "^1"
},
"require-dev": {
"phpunit/phpunit": "^6",
"amphp/phpunit-util": "^1",
"friendsofphp/php-cs-fixer": "^2.3",
"kelunik/fqn-check": "^0.1.3"
},
"license": "MIT",
"authors": [
{
"name": "Bob Weinand",
"email": "bobwei9@hotmail.com"
},
{
"name": "Aaron Piotrowski",
"email": "aaron@trowski.com"
}
],
"autoload": {
"psr-4": {
"Amp\\Process\\": "lib"
}
}
}
PK 5dAV?s‘ test/ProcessTest.phpnu W+A„¶ start();
$process->start();
});
}
public function testIsRunning() {
Loop::run(function () {
$process = new Process("exit 42");
$process->start();
$promise = $process->join();
$this->assertTrue($process->isRunning());
yield $promise;
$this->assertFalse($process->isRunning());
});
}
public function testExecuteResolvesToExitCode() {
Loop::run(function () {
$process = new Process("exit 42");
$process->start();
$code = yield $process->join();
$this->assertSame(42, $code);
$this->assertFalse($process->isRunning());
});
}
public function testCommandCanRun() {
Loop::run(function () {
$process = new Process(self::CMD_PROCESS);
$process->start();
$promise = $process->join();
$completed = false;
$promise->onResolve(function () use (&$completed) { $completed = true; });
$this->assertFalse($completed);
$this->assertInternalType('int', $process->getPid());
});
}
/**
* @expectedException \Amp\Process\ProcessException
* @expectedExceptionMessage The process was killed
*/
public function testKillSignals() {
Loop::run(function () {
$process = new Process(self::CMD_PROCESS);
$process->start();
$promise = $process->join();
$process->kill();
$code = yield $promise;
});
}
public function testCommand() {
$process = new Process(self::CMD_PROCESS);
$this->assertSame(self::CMD_PROCESS, $process->getCommand());
}
public function testOptions() {
$process = new Process(self::CMD_PROCESS);
$this->assertSame([], $process->getOptions());
}
}
PK 5dAV^/Þ` ` examples/basic-command.phpnu W+A„¶ start();
echo yield new Message($process->getStdout());
$code = yield $process->join();
echo "Process exited with {$code}.\n";
});
PK 5dAVÒ™¶Ž£ £ examples/write-command.phpnu W+A„¶ start();
/* send to stdin */
$process->getStdin()->write("abc\n");
echo yield new Message($process->getStdout());
$code = yield $process->join();
echo "Process exited with {$code}.\n";
});
PK 5dAVœ×ò› › examples/watch-live.phpnu W+A„¶ start();
$stream = $process->getStdout();
while ($chunk = yield $stream->read()) {
echo $chunk;
}
$code = yield $process->join();
echo "Process exited with {$code}.\n";
});
PK 5dAV`¦sk5 5
.gitignorenu W+A„¶ build
composer.lock
phpunit.xml
vendor
.php_cs.cache
PK 5dAV<
ÈŒ€ € README.mdnu W+A„¶ # Process
An async process dispatcher built on the amp concurrency framework
[![Build Status](https://img.shields.io/travis/amphp/process/v0.2.x.svg?style=flat-square)](https://travis-ci.org/amphp/process)
[![Coverage Status](https://img.shields.io/coveralls/amphp/process/v0.2.x.svg?style=flat-square)](https://coveralls.io/github/amphp/process?branch=v0.2.x)
![Stable](https://img.shields.io/badge/v0.2-stable-green.svg?style=flat-square)
![License](https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square)
## Installation
This package can be installed as a [Composer](https://getcomposer.org/) dependency.
```bash
composer require amphp/process
```
## Requirements
* PHP 7.0+
* [Amp framework](https://github.com/amphp/amp) (installed via composer)
## Versioning
`amphp/process` follows the [semver](http://semver.org/) semantic versioning specification like all other `amphp` packages.
## Security
If you discover any security related issues, please email [`me@kelunik.com`](mailto:me@kelunik.com) instead of using the issue tracker.
## License
The MIT License (MIT). Please see [`LICENSE`](./LICENSE) for more information.
PK 5dAV›Ñ>_ _ phpunit.xml.distnu W+A„¶ PK 5dAVTÌëuM M Ÿ lib/ProcessException.phpnu W+A„¶ PK 5dAVBcHD D 4 lib/StatusError.phpnu W+A„¶ PK 5dAVÁ4Å., ., » lib/Process.phpnu W+A„¶ PK 5dAVÛ4)u u (1 LICENSEnu W+A„¶ PK 5dAV»88E§ § Ô5 .travis.ymlnu W+A„¶ PK 5dAVç¥s s ¶8 .php_csnu W+A„¶ PK 5dAVmºámà à
`> composer.jsonnu W+A„¶ PK 5dAV?s‘ }A test/ProcessTest.phpnu W+A„¶ PK 5dAV^/Þ` ` ÌJ examples/basic-command.phpnu W+A„¶ PK 5dAVÒ™¶Ž£ £ vL examples/write-command.phpnu W+A„¶ PK 5dAVœ×ò› › cN examples/watch-live.phpnu W+A„¶ PK 5dAV`¦sk5 5
EP .gitignorenu W+A„¶ PK 5dAV<
ÈŒ€ € ´P README.mdnu W+A„¶ PK b mU