1
0
mirror of https://github.com/danog/process.git synced 2024-11-30 04:39:04 +01:00

Close unnecessary file descriptors in child process

This commit is contained in:
Aaron Piotrowski 2019-01-23 12:44:43 -06:00
parent e7e28219da
commit a461b7d975
No known key found for this signature in database
GPG Key ID: ADD1EF783EDE9EEB

View File

@ -23,6 +23,10 @@ final class Runner implements ProcessRunner
["pipe", "w"], // stderr
["pipe", "w"], // exit code pipe
];
const FD_COUNT = 4;
/** @var string|null */
private static $fdPath;
public static function onProcessEndExtraDataPipeReadable($watcher, $stream, Handle $handle)
{
@ -82,7 +86,7 @@ final class Runner implements ProcessRunner
);
$handle = new Handle;
$handle->proc = @\proc_open($command, self::FD_SPEC, $pipes, $cwd ?: null, $env ?: null, $options);
$handle->proc = @\proc_open($command, $this->generateFds(), $pipes, $cwd ?: null, $env ?: null, $options);
if (!\is_resource($handle->proc)) {
$message = "Could not start process";
@ -127,6 +131,28 @@ final class Runner implements ProcessRunner
return $handle;
}
private function generateFds(): array
{
if (self::$fdPath === null) {
self::$fdPath = \file_exists("/dev/fd") ? "/dev/fd" : "/proc/self/fd";
}
$fds = @\scandir(self::$fdPath, \SCANDIR_SORT_NONE);
if ($fds === false) {
throw new ProcessException("Unable to list open file descriptors");
}
$fds = \array_filter($fds, function (string $path): bool {
return $path !== "." && $path !== "..";
});
return \array_merge(
self::FD_SPEC,
\array_fill(self::FD_COUNT, \count($fds) - self::FD_COUNT, ["file", "/dev/null", "r"])
);
}
/** @inheritdoc */
public function join(ProcessHandle $handle): Promise
{