Files
nih-php-command-builder/src/Child.php

74 lines
1.7 KiB
PHP

<?php
declare(strict_types=1);
namespace Nih\CommandBuilder;
final class Child
{
/**
* @param resource $proc The process handle.
*/
public function __construct(
public readonly ?ChildStdin $stdin,
public readonly ?ChildStdout $stdout,
public readonly ?ChildStderr $stderr,
public $proc,
) {
}
public function id(): int
{
if (!is_resource($this->proc)) {
throw new ChildException('Resource was already closed');
}
$status = proc_get_status($this->proc);
return $status['pid'];
}
public function waitWithOutput(): Output
{
if (!is_resource($this->proc)) {
throw new ChildException('Resource was already closed');
}
// Avoid possible deadlock before waiting.
$this->stdin?->close();
$stdout = $this->stdout?->getContents();
$stderr = $this->stderr?->getContents();
$status = new ExitStatus(proc_close($this->proc));
return new Output($stdout, $stderr, $status);
}
public function wait(): ExitStatus
{
if (!is_resource($this->proc)) {
throw new ChildException('Resource was already closed');
}
// Avoid possible deadlock before waiting.
$this->stdin?->close();
return new ExitStatus(proc_close($this->proc));
}
public function kill(): bool
{
if (!is_resource($this->proc)) {
throw new ChildException('Resource was already closed');
}
return proc_terminate($this->proc, 10);
}
public function __destruct()
{
if (is_resource($this->proc)) {
proc_close($this->proc);
}
}
}