Skip to content

Core\Process::spawn

Core\Process::spawn(
    string $path,
    array<string> $argv,
    {workingDirectory?: string, env?: array<string>, timeout?: Core\Time\Duration},
): Core\Process\Handle

Starts another program and returns at once, while the program is still running. You get a Core\Process\Handle. With it you read the output a part at a time, and you write to the input. wait() waits for the end and returns a Core\Process\Result with the exit code.

Use Core\Process::run when you only need the output at the end. Use spawn for output as it arrives, or for a program that reads your input.

The program starts directly, never through a shell. Each array element is one argument. A command-line program may run any program. On a server, the process.exec capability in nvs.toml must name the program or its folder. Otherwise spawn throws a RuntimeError.

Call wait() or kill() before your script or request ends. If the program still runs when they end, it is stopped and an error is reported. With nvs run, the exit code is 1. With nvs serve, the error is in the request log.

A program started inside a Core\Task child task is stopped when that task ends, and an error is reported. The exit code does not change. A handle works only in the task that called spawn.

Parameters

  • $pathstringThe program to start, as an absolute path. A relative path must be a string written directly in the code. It is joined to the folder of the file that contains it. PATH is not searched.
  • $argvarray<string>The arguments, one in each element. An element with a space, a quote or a ; in it is still one argument, on every platform.

Options

  • workingDirectorystringoptionalThe folder the program starts in, as an absolute path. A relative path must be written directly in the code, and is joined to the folder of this file. Without it, the program starts in the same folder as this program.
  • envarray<string>optionalThe environment variables of the program, as name => value. This replaces all of them, so a variable that is not in the array is not set. Without it, the program gets only these variables from this program: PATH, HOME or USERPROFILE, TEMP, TMP, LANG, and SYSTEMROOT on Windows. A secret value is a value the program must keep hidden, such as a password. Call Core\Secret::reveal on it first.
  • timeoutCore\Time\DurationoptionalThe longest time the program may run, counted from the start. When it passes, the program is stopped, and the next call on the handle throws a TimeoutError.

Return value

Returns Core\Process\Handle. A Core\Process\Handle for the running program. Other requests keep running while this one waits on the handle. Call wait or kill on it before your script or request ends. If the program is still running when the script or request ends, it is stopped and Novis reports an error.

Errors

  • RuntimeErrorprocess.exec does not allow this program, or it is a .bat, .cmd or .ps1 file. Those are not allowed on any platform, because Windows starts them through a shell. It is also thrown when workingDirectory is a relative path, or when timeout is zero or shorter. An env name that is empty or has a = in it throws it too.
  • IOErrorThe program could not be started. For example, nothing is at the path, the file is not a program, or the workingDirectory folder does not exist.

Changelog

VersionChange
0.0.6The option cwd of Core\Process::run and Core\Process::spawn is now workingDirectory. The option args of Core\Queue::push is now arguments.

Examples

The examples below run with this configuration file.

nvs.toml
# These lines allow only the two programs the examples run, `/usr/bin/seq` and `/usr/bin/sort`.
# Without them, a program run with `nvs run` may run any program.
[capabilities.process]
exec = ["/usr/bin/seq", "/usr/bin/sort"]

Reading output as it arrives

<?nvs
// Shows how to read what a program prints while it is still running.
// requires: unix
// `seq 1 3` prints the numbers 1, 2 and 3, one on each line.
// `spawn` returns at once. The program is still running.
var $numbers = Core\Process::spawn('/usr/bin/seq', ['1', '3']);
// `readStdout()` returns the next part of the output, as `bytes`.
// It returns `null` when the program has closed its output.
?tainted bytes $part = $numbers->readStdout();
while ($part != null) {
echo $part as string;
$part = $numbers->readStdout();
}
// `wait()` waits until the program ends. This prints `0`.
echo $numbers->wait()->exitCode(), "\n";
Output
1
2
3
0

A program that is not allowed

<?nvs
// Shows what happens when a program is not in the folders that `nvs.toml` allows.
// `nvs.toml` allows `/bin` and `/usr/bin`. `/opt/backup/bin/backup` is in neither folder.
// So `Core\Process::spawn` throws a `RuntimeError`. The program is not started, and there is no handle.
try {
var $backup = Core\Process::spawn('/opt/backup/bin/backup', ['--all']);
echo 'The program ended with exit code ', $backup->wait()->exitCode(), ".\n";
} catch (RuntimeError $notAllowed) {
echo "The program was not started.\n";
}
Output
The program was not started.

Sorting lines with a tool

<?nvs
// Shows a small method that sends text to a tool's input and returns what the tool prints.
// requires: unix
class Tools
{
public static function filter(string $path, array<string> $arguments, string $input): tainted string
{
var $tool = Core\Process::spawn($path, $arguments);
// `writeStdin` sends the text to the tool. A `string` converts to `bytes` here.
$tool->writeStdin($input as bytes);
// `wait()` closes the tool's input, so the tool knows the text is complete.
// Then it waits for the tool to end, and returns its exit code and output.
var $result = $tool->wait();
if ($result->exitCode() != 0) {
throw new RuntimeError('the tool failed with exit code ' . $result->exitCode());
}
return $result->stdout() as string;
}
}
// `sort` prints the lines in order. This prints apple, fig and pear.
echo Tools::filter('/usr/bin/sort', [], "pear\napple\nfig\n");
// `-r` sorts in reverse order. This prints pear, fig and apple.
echo Tools::filter('/usr/bin/sort', ['-r'], "pear\napple\nfig\n");
Output
apple
fig
pear
pear
fig
apple