Programming Search⌘K

Taskcore

Run a subprocess

Also called run an external command, run a program and capture its output, spawn a child process, exec a command.

Start a program with a list of arguments and no shell, read its standard output and standard error, and return its exit status. A missing program is an error.

Task

Run a program, wait for it to exit, and return what it did. The result has three parts: the exit status, the text on standard output and the text on standard error.

Each solution is a function run(argv). The first element of argv is the program, and the other elements are its arguments. The solution finds the program through PATH and starts it with no shell, so each argument reaches the program as one string with no change. The standard input of the program is empty, so a read gets end of file at once. The program gets the environment and the working directory of the caller.

A status that is not 0 is a result, not an error. A program that is not in PATH is an error, because no status exists. A program that a signal stops is outside the contract. Each solution reports it in its own way.

The program can write to both streams at the same time. A pipe holds a limited amount of data. So the solution must read both pipes while the program runs. If it reads one pipe to its end first, the program can block on the other pipe, and the two processes wait for ever.

Solutions

Each solution passes a list of arguments, captures the two streams, and reads them at the same time.

  • Python. subprocess.run(argv, stdin=subprocess.DEVNULL, capture_output=True, encoding="utf-8"). run waits for the program and returns all of its output. shell is false by default. A missing program raises FileNotFoundError, a subclass of OSError. A status that is not 0 raises an exception only with check=True.
  • JavaScript and TypeScript (Node.js). spawnSync(file, args, {stdio: ["ignore", "pipe", "pipe"], encoding: "utf8", maxBuffer: Infinity}). 'ignore' attaches /dev/null to the standard input of the child. A missing program sets result.error with the code ENOENT, and the solution throws it. result.status is null when a signal stopped the child. The TypeScript file adds types only.
  • Java. new ProcessBuilder(argv).start(). The solution closes getOutputStream(), the standard input of the child. It reads standard error on a second thread and standard output on the calling thread, and then calls waitFor. A missing program throws an IOException.
  • C#. A ProcessStartInfo with UseShellExecute = false and the three Redirect properties set to true. Each argument goes into ArgumentList, which does the quoting. The solution reads standard error with ReadToEndAsync and standard output with ReadToEnd. A missing program throws a Win32Exception.
  • Go. exec.Command(argv[0], argv[1:]...) with two strings.Builder values as Stdout and Stderr. A writer that is not a file makes the package copy the pipe on its own goroutine. A nil Stdin reads from the null device. Run returns an *exec.ExitError for a status that is not 0, and the solution takes the status from cmd.ProcessState.ExitCode(). A missing program gives an error that wraps exec.ErrNotFound.
  • Rust. Command::new(program).args(args).output(). output collects both streams, waits for the child, and closes its standard input. It returns Ok also for a status that is not 0. status.code() is None when a signal stopped the child. A missing program gives an io::Error of the kind NotFound.
  • C. The solution uses POSIX. posix_spawnp searches PATH and starts the program. Its file actions open /dev/null as file descriptor 0 and connect 1 and 2 to two pipes. A poll loop reads both pipes until each gives end of file. Then waitpid, WIFEXITED and WEXITSTATUS give the status.
  • C++. The same POSIX calls, with std::string buffers and a class that closes each file descriptor. A missing program throws std::system_error with std::errc::no_such_file_or_directory.
  • Bash. run_program STATUS OUT ERR program args... stores the three results in the variables that the caller names. type -P searches PATH for a file, so the solution runs the printf program in PATH and not the builtin printf. The program writes to two temporary files, and the solution reads them back. The function name is not run, because bats uses that name.

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl. The case that must give an error is in cases/errors.jsonl.

  • metacharacters: the arguments a b, $HOME, *, x;y, "q" and 's' reach printf with no change. With no shell, nothing expands them.
  • empty-argument: an empty string is one argument. A command line in one string loses it.
  • newline-argument: an argument can hold a newline.
  • trailing-newlines: the output a\n\n comes back with both newlines. Shell command substitution removes them.
  • non-ascii: the program writes UTF-8 text with characters of 2, 3 and 4 bytes.
  • stderr-only and both-streams: the two streams stay apart.
  • false and status-255: a status that is not 0 is a result. A status has 8 bits, so 255 is the largest value.
  • empty-stdin: read in the child gets end of file at once.
  • missing-program: no program has the name. Each solution reports the error, not a status. POSIX lets posix_spawnp start the child and then fail in it, and the child then exits with the status 127. So the C and C++ tests accept the status 127 or the error ENOENT.
  • Large output: JSON cannot hold it, so each test also runs a program that writes 1 MiB to standard output and then 1 MiB to standard error. A solution that reads standard output to its end before it reads standard error blocks on this program.

Pitfalls

  • One string through a shell. A command line in one string goes through a shell. The shell splits words, expands variables and removes empty arguments. The list form passes each argument as one string:
import subprocess

arg = "two  spaces $NO_SUCH_VAR_7F3A end"
listed = subprocess.run(["printf", "[%s]\n", arg], capture_output=True, text=True)
print("list: ", listed.stdout, end="")
shelled = subprocess.run(f"printf '[%s]\\n' {arg}", shell=True, capture_output=True, text=True)
print("shell:", " ".join(shelled.stdout.split()))
Output
list:  [two  spaces $NO_SUCH_VAR_7F3A end]
shell: [two] [spaces] [end]

When the string holds input from a user, this is also OS command injection. Python shell=True, Node.js exec and bash -c with a joined string all start a shell. Node.js execFile and spawn do not start a shell by default.

  • A status that is not 0 passes in silence. Most of the functions return a result for a failed program and do not throw. The caller must check the status. Python raises CalledProcessError only with check=True:
import subprocess

result = subprocess.run(["sh", "-c", "echo partial; exit 1"], capture_output=True, text=True)
print(repr(result.stdout), result.returncode)
try:
    subprocess.run(["sh", "-c", "exit 1"], check=True)
except subprocess.CalledProcessError as e:
    print("CalledProcessError", e.returncode)
Output
'partial\n' 1
CalledProcessError 1

Rust output returns Ok, Go Run returns an *ExitError, and Node.js spawnSync sets status. In Java and C#, read waitFor() or ExitCode.

  • A wait before the read. A child that fills a pipe blocks until the parent reads. A parent that waits for the child before it reads waits for ever. The Python documentation gives this warning for Popen.wait and says to use communicate. The Java and .NET documentation give the same warning:

This code does not stop, on purpose.

import subprocess

proc = subprocess.Popen(["sh", "-c", "head -c 1048576 /dev/zero"], stdout=subprocess.PIPE)
proc.wait()
print(len(proc.stdout.read()))

Two reads in sequence can also block: the parent waits for the end of standard output, and the child waits for space in the pipe of standard error. Read the two streams on two threads, with asynchronous reads, or with poll.

  • The size limit of spawnSync. maxBuffer is 1 MiB on each stream by default. Past the limit, Node.js stops the child and cuts the output:
import { spawnSync } from "node:child_process";

const script = "head -c 2097152 /dev/zero | tr '\\0' x; echo done >&2";
const r = spawnSync("sh", ["-c", script], { encoding: "utf8" });
console.log(r.status, r.signal, r.error?.code);
console.log(r.stdout.length < 2097152);
Output
null SIGTERM ENOBUFS
true
  • Trailing newlines in Bash. $(...) removes all of the newlines at the end of the output. Add a character after the output, and remove it from the result:
out=$(printf 'a\n\n')
printf '[%s]\n' "$out"
out=$(printf 'a\n\n'; printf x)
out=${out%x}
printf '[%s]\n' "$out"
Output
[a]
[a

]
  • A status after a signal. POSIX gives a status only to a child that exits. Python sets returncode to minus the signal number. Go ExitCode returns -1. Node.js sets status to null and puts the name in signal. A shell gives a status greater than 128, and Bash uses 128 plus the signal number. So the value -9 or -1 can look like a status:
import subprocess

print(subprocess.run(["sh", "-c", "kill -9 $$"]).returncode)
Output
-9
package main

import (
	"fmt"
	"os/exec"
)

func main() {
	cmd := exec.Command("sh", "-c", "kill -9 $$")
	err := cmd.Run()
	fmt.Println(cmd.ProcessState.ExitCode(), err)
}
Output
-1 signal: killed
  • What the child gets from the parent. The child gets a copy of the environment and the working directory of the parent. In Go, a nil Env and an empty Dir give these values. In Java, environment() starts as a copy of the environment of the parent. To change a value for the child only, set it on the command, not in the parent. See Read an environment variable.

Code

The build runs the native tests of each language in a pinned toolchain.

run.pyI0tests passRawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/run-a-subprocess/.

import subprocess


def run(argv: list[str]) -> tuple[int, str, str]:
    """Run argv with no shell and return (status, stdout, stderr).

    A missing program raises FileNotFoundError. A status that is not 0
    is a result, so check is False.
    """
    result = subprocess.run(
        argv,
        stdin=subprocess.DEVNULL,
        capture_output=True,
        encoding="utf-8",
        check=False,
    )
    if result.returncode < 0:
        raise ChildProcessError(f"{argv[0]} was stopped by signal {-result.returncode}")
    return result.returncode, result.stdout, result.stderr
test_run.py 54 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/run-a-subprocess/.

import pytest

from run import run

# name: (argv, expected (status, stdout, stderr))
CASES = {
    "hello": (["printf", "hello"], (0, "hello", "")),
    "two-arguments": (["echo", "one", "two"], (0, "one two\n", "")),
    "exit-status": (["sh", "-c", "exit 3"], (3, "", "")),
    "both-streams": (["sh", "-c", "echo out; echo err >&2; exit 2"], (2, "out\n", "err\n")),
    "metacharacters": (
        ["printf", "%s|", "a b", "$HOME", "*", "x;y", '"q"', "'s'"],
        (0, "a b|$HOME|*|x;y|\"q\"|'s'|", ""),
    ),
    "empty-argument": (["printf", "[%s]", ""], (0, "[]", "")),
    "newline-argument": (["printf", "%s", "line one\nline two"], (0, "line one\nline two", "")),
    "trailing-newlines": (["printf", "a\\n\\n"], (0, "a\n\n", "")),
    "non-ascii": (["printf", "%s\\n", "xin chào, 日本語, 🙂"], (0, "xin chào, 日本語, 🙂\n", "")),
    "stderr-only": (["sh", "-c", "echo warning >&2"], (0, "", "warning\n")),
    "no-output": (["true"], (0, "", "")),
    "false": (["false"], (1, "", "")),
    "status-255": (["sh", "-c", "exit 255"], (255, "", "")),
    "empty-stdin": (
        ["sh", "-c", "if read -r line; then echo got; else echo eof; fi"],
        (0, "eof\n", ""),
    ),
}


@pytest.mark.parametrize("name", CASES)
def test_cases(name):
    argv, want = CASES[name]
    assert run(argv) == want


def test_large_output_on_both_streams():
    script = "head -c 1048576 /dev/zero | tr '\\0' x; head -c 1048576 /dev/zero | tr '\\0' y >&2"
    status, out, err = run(["sh", "-c", script])
    assert status == 0
    assert out == "x" * 1048576
    assert err == "y" * 1048576


def test_missing_program():
    with pytest.raises(FileNotFoundError):
        run(["no-such-program-7f3a"])


def test_signal():
    with pytest.raises(ChildProcessError):
        run(["sh", "-c", "kill -9 $$"])
run.cppI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/run-a-subprocess/.

#include "run.hpp"

#include <array>
#include <cerrno>
#include <fcntl.h>
#include <poll.h>
#include <spawn.h>
#include <stdexcept>
#include <sys/wait.h>
#include <system_error>
#include <unistd.h>

extern char **environ;

namespace {

[[noreturn]] void fail(int code, const char *what) {
    throw std::system_error(code, std::generic_category(), what);
}

// Closes a file descriptor when it goes out of scope.
class Fd {
  public:
    explicit Fd(int fd = -1) : fd_(fd) {}
    Fd(const Fd &) = delete;
    Fd &operator=(const Fd &) = delete;
    ~Fd() { reset(); }
    int get() const { return fd_; }
    void reset(int fd = -1) {
        if (fd_ >= 0) {
            close(fd_);
        }
        fd_ = fd;
    }

  private:
    int fd_;
};

void make_pipe(Fd &read_end, Fd &write_end) {
    int fds[2];
    if (pipe(fds) != 0) {
        fail(errno, "pipe");
    }
    read_end.reset(fds[0]);
    write_end.reset(fds[1]);
    // The pipes must not leak into other children.
    fcntl(fds[0], F_SETFD, FD_CLOEXEC);
    fcntl(fds[1], F_SETFD, FD_CLOEXEC);
}

} // namespace

RunResult run(const std::vector<std::string> &argv) {
    // posix_spawnp takes an array of char pointers that ends with a null pointer.
    std::vector<char *> args;
    for (const auto &arg : argv) {
        args.push_back(const_cast<char *>(arg.c_str()));
    }
    args.push_back(nullptr);

    Fd out_read, out_write, err_read, err_write;
    make_pipe(out_read, out_write);
    make_pipe(err_read, err_write);

    posix_spawn_file_actions_t actions;
    posix_spawn_file_actions_init(&actions);
    posix_spawn_file_actions_addopen(&actions, 0, "/dev/null", O_RDONLY, 0);
    // dup2 clears FD_CLOEXEC on the new descriptor, so 1 and 2 stay open.
    posix_spawn_file_actions_adddup2(&actions, out_write.get(), 1);
    posix_spawn_file_actions_adddup2(&actions, err_write.get(), 2);
    pid_t pid;
    int rc = posix_spawnp(&pid, args[0], &actions, nullptr, args.data(), environ);
    posix_spawn_file_actions_destroy(&actions);
    out_write.reset();
    err_write.reset();
    if (rc != 0) {
        fail(rc, args[0]);
    }

    // Read the two pipes as data comes. If this loop read one pipe to its
    // end first, a child that fills the other pipe would block for ever.
    RunResult result{0, {}, {}};
    std::array<std::string *, 2> sinks{&result.out, &result.err};
    std::array<pollfd, 2> fds{pollfd{out_read.get(), POLLIN, 0}, pollfd{err_read.get(), POLLIN, 0}};
    std::array<char, 65536> chunk;
    int failed = 0;
    for (int open_fds = 2; open_fds > 0 && failed == 0;) {
        if (poll(fds.data(), fds.size(), -1) < 0) {
            if (errno != EINTR) {
                failed = errno;
            }
            continue;
        }
        for (std::size_t i = 0; i < fds.size(); i++) {
            if (fds[i].fd < 0 || fds[i].revents == 0) {
                continue;
            }
            ssize_t n = read(fds[i].fd, chunk.data(), chunk.size());
            if (n > 0) {
                sinks[i]->append(chunk.data(), static_cast<std::size_t>(n));
            } else if (n == 0) {
                fds[i].fd = -1; // a negative fd makes poll skip the entry
                open_fds--;
            } else if (errno != EINTR) {
                failed = errno;
            }
        }
    }
    out_read.reset();
    err_read.reset();

    int wstatus;
    while (waitpid(pid, &wstatus, 0) < 0) {
        if (errno != EINTR) {
            fail(errno, "waitpid");
        }
    }
    if (failed != 0) {
        fail(failed, "read");
    }
    if (!WIFEXITED(wstatus)) {
        throw std::runtime_error(argv[0] + " was stopped by signal " + std::to_string(WTERMSIG(wstatus)));
    }
    result.status = WEXITSTATUS(wstatus);
    return result;
}
run.hpp 25 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/run-a-subprocess/.

#ifndef RUN_HPP
#define RUN_HPP

#include <string>
#include <vector>

struct RunResult {
    int status;
    std::string out;
    std::string err;

    bool operator==(const RunResult &) const = default;
};

// run starts argv[0] with the arguments argv. It searches PATH for argv[0]
// and starts no shell. The standard input of the child is /dev/null. A
// missing program throws std::system_error with the code
// std::errc::no_such_file_or_directory. A child that a signal stops throws
// std::runtime_error.
RunResult run(const std::vector<std::string> &argv);

#endif
test_run.cpp 82 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/run-a-subprocess/.

#include "run.hpp"

#include <iostream>
#include <stdexcept>
#include <string>
#include <system_error>
#include <vector>

struct TestCase {
    std::string name;
    std::vector<std::string> argv;
    RunResult want;
};

int main() {
    const std::vector<TestCase> cases{
        {"hello", {"printf", "hello"}, {0, "hello", ""}},
        {"two-arguments", {"echo", "one", "two"}, {0, "one two\n", ""}},
        {"exit-status", {"sh", "-c", "exit 3"}, {3, "", ""}},
        {"both-streams", {"sh", "-c", "echo out; echo err >&2; exit 2"}, {2, "out\n", "err\n"}},
        {"metacharacters",
         {"printf", "%s|", "a b", "$HOME", "*", "x;y", "\"q\"", "'s'"},
         {0, "a b|$HOME|*|x;y|\"q\"|'s'|", ""}},
        {"empty-argument", {"printf", "[%s]", ""}, {0, "[]", ""}},
        {"newline-argument", {"printf", "%s", "line one\nline two"}, {0, "line one\nline two", ""}},
        {"trailing-newlines", {"printf", "a\\n\\n"}, {0, "a\n\n", ""}},
        {"non-ascii", {"printf", "%s\\n", "xin chào, 日本語, 🙂"}, {0, "xin chào, 日本語, 🙂\n", ""}},
        {"stderr-only", {"sh", "-c", "echo warning >&2"}, {0, "", "warning\n"}},
        {"no-output", {"true"}, {0, "", ""}},
        {"false", {"false"}, {1, "", ""}},
        {"status-255", {"sh", "-c", "exit 255"}, {255, "", ""}},
        {"empty-stdin", {"sh", "-c", "if read -r line; then echo got; else echo eof; fi"}, {0, "eof\n", ""}},
    };
    int failures = 0;
    for (const auto &c : cases) {
        try {
            if (run(c.argv) != c.want) {
                std::cout << "FAIL " << c.name << '\n';
                failures++;
            }
        } catch (const std::exception &e) {
            std::cout << "FAIL " << c.name << ": " << e.what() << '\n';
            failures++;
        }
    }

    const std::string script = "head -c 1048576 /dev/zero | tr '\\0' x; head -c 1048576 /dev/zero | tr '\\0' y >&2";
    if (run({"sh", "-c", script}) != RunResult{0, std::string(1048576, 'x'), std::string(1048576, 'y')}) {
        std::cout << "FAIL large-output\n";
        failures++;
    }

    try {
        auto r = run({"no-such-program-7f3a"});
        // POSIX allows posix_spawnp to succeed and the child to exit with 127.
        if (r.status != 127) {
            std::cout << "FAIL missing-program: status " << r.status << '\n';
            failures++;
        }
    } catch (const std::system_error &e) {
        if (e.code() != std::errc::no_such_file_or_directory) {
            std::cout << "FAIL missing-program: " << e.what() << '\n';
            failures++;
        }
    }

    try {
        run({"sh", "-c", "kill -9 $$"});
        std::cout << "FAIL signal: no exception\n";
        failures++;
    } catch (const std::runtime_error &) {
    }

    if (failures > 0) {
        return 1;
    }
    std::cout << "all cases pass\n";
    return 0;
}
RunProcess.javaI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/run-a-subprocess/.

import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;

/** Runs a program with an argument list and no shell. */
public final class RunProcess {
  private RunProcess() {}

  /** The exit status and the text of the two output streams. */
  public record Result(int status, String stdout, String stderr) {}

  /**
   * Runs argv and returns its result. A missing program throws an IOException. A status that is
   * not 0 is a result, not an exception.
   */
  public static Result run(List<String> argv) throws IOException, InterruptedException {
    Process process = new ProcessBuilder(argv).start();
    // Close the standard input of the child, so a read gets end of file.
    process.getOutputStream().close();
    // Read standard error on a second thread. If this thread reads one
    // stream to its end first, a child that fills the other pipe blocks.
    CompletableFuture<String> stderr =
        CompletableFuture.supplyAsync(() -> readAll(process.getErrorStream()));
    String stdout = readAll(process.getInputStream());
    int status = process.waitFor();
    try {
      return new Result(status, stdout, stderr.join());
    } catch (CompletionException e) {
      throw new IOException("cannot read standard error", e.getCause());
    }
  }

  private static String readAll(InputStream in) {
    try (in) {
      return new String(in.readAllBytes(), StandardCharsets.UTF_8);
    } catch (IOException e) {
      throw new UncheckedIOException(e);
    }
  }
}
RunProcessTest.java 80 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/run-a-subprocess/.

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

import java.io.IOException;
import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class RunProcessTest {
  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("hello", List.of("printf", "hello"), 0, "hello", ""),
        Arguments.of("two-arguments", List.of("echo", "one", "two"), 0, "one two\n", ""),
        Arguments.of("exit-status", List.of("sh", "-c", "exit 3"), 3, "", ""),
        Arguments.of(
            "both-streams",
            List.of("sh", "-c", "echo out; echo err >&2; exit 2"),
            2,
            "out\n",
            "err\n"),
        Arguments.of(
            "metacharacters",
            List.of("printf", "%s|", "a b", "$HOME", "*", "x;y", "\"q\"", "'s'"),
            0,
            "a b|$HOME|*|x;y|\"q\"|'s'|",
            ""),
        Arguments.of("empty-argument", List.of("printf", "[%s]", ""), 0, "[]", ""),
        Arguments.of(
            "newline-argument",
            List.of("printf", "%s", "line one\nline two"),
            0,
            "line one\nline two",
            ""),
        Arguments.of("trailing-newlines", List.of("printf", "a\\n\\n"), 0, "a\n\n", ""),
        Arguments.of(
            "non-ascii",
            List.of("printf", "%s\\n", "xin chào, 日本語, 🙂"),
            0,
            "xin chào, 日本語, 🙂\n",
            ""),
        Arguments.of("stderr-only", List.of("sh", "-c", "echo warning >&2"), 0, "", "warning\n"),
        Arguments.of("no-output", List.of("true"), 0, "", ""),
        Arguments.of("false", List.of("false"), 1, "", ""),
        Arguments.of("status-255", List.of("sh", "-c", "exit 255"), 255, "", ""),
        Arguments.of(
            "empty-stdin",
            List.of("sh", "-c", "if read -r line; then echo got; else echo eof; fi"),
            0,
            "eof\n",
            ""));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void runsTheProgram(String name, List<String> argv, int status, String stdout, String stderr)
      throws IOException, InterruptedException {
    assertEquals(new RunProcess.Result(status, stdout, stderr), RunProcess.run(argv), name);
  }

  @Test
  void largeOutputOnBothStreams() throws IOException, InterruptedException {
    String script =
        "head -c 1048576 /dev/zero | tr '\\0' x; head -c 1048576 /dev/zero | tr '\\0' y >&2";
    RunProcess.Result result = RunProcess.run(List.of("sh", "-c", script));
    assertEquals(0, result.status());
    assertEquals("x".repeat(1048576), result.stdout());
    assertEquals("y".repeat(1048576), result.stderr());
  }

  @Test
  void missingProgram() {
    assertThrows(IOException.class, () -> RunProcess.run(List.of("no-such-program-7f3a")));
  }
}
run.cI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/run-a-subprocess/.

#define _POSIX_C_SOURCE 200809L

#include "run.h"

#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <spawn.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>

extern char **environ;

struct buffer {
    char *data;
    size_t len, cap;
};

// append reads once from fd into b. It returns 1 after data, 0 at end of
// file, and -1 on an error.
static int append(int fd, struct buffer *b) {
    if (b->cap - b->len < 4096) {
        size_t cap = b->cap ? b->cap * 2 : 8192;
        char *data = realloc(b->data, cap);
        if (data == nullptr) {
            return -1;
        }
        b->data = data;
        b->cap = cap;
    }
    // Keep one byte for the final NUL.
    ssize_t n = read(fd, b->data + b->len, b->cap - b->len - 1);
    if (n < 0) {
        return errno == EINTR ? 1 : -1;
    }
    b->len += (size_t)n;
    return n > 0;
}

static int pipe_cloexec(int fds[2]) {
    if (pipe(fds) != 0) {
        return -1;
    }
    // The pipes must not leak into other children.
    fcntl(fds[0], F_SETFD, FD_CLOEXEC);
    fcntl(fds[1], F_SETFD, FD_CLOEXEC);
    return 0;
}

int run(char *const argv[], struct run_result *result) {
    int out[2], err[2];
    if (pipe_cloexec(out) != 0) {
        return -1;
    }
    if (pipe_cloexec(err) != 0) {
        int saved = errno;
        close(out[0]);
        close(out[1]);
        errno = saved;
        return -1;
    }

    posix_spawn_file_actions_t actions;
    posix_spawn_file_actions_init(&actions);
    posix_spawn_file_actions_addopen(&actions, 0, "/dev/null", O_RDONLY, 0);
    // dup2 clears FD_CLOEXEC on the new descriptor, so 1 and 2 stay open.
    posix_spawn_file_actions_adddup2(&actions, out[1], 1);
    posix_spawn_file_actions_adddup2(&actions, err[1], 2);
    pid_t pid;
    int rc = posix_spawnp(&pid, argv[0], &actions, nullptr, argv, environ);
    posix_spawn_file_actions_destroy(&actions);
    close(out[1]);
    close(err[1]);
    if (rc != 0) {
        close(out[0]);
        close(err[0]);
        errno = rc;
        return -1;
    }

    // Read the two pipes as data comes. If this loop read one pipe to its
    // end first, a child that fills the other pipe would block for ever.
    struct buffer bufs[2] = {0};
    struct pollfd fds[2] = {{.fd = out[0], .events = POLLIN}, {.fd = err[0], .events = POLLIN}};
    int open_fds = 2, failed = 0;
    while (open_fds > 0 && !failed) {
        if (poll(fds, 2, -1) < 0) {
            if (errno == EINTR) {
                continue;
            }
            failed = errno;
            break;
        }
        for (int i = 0; i < 2; i++) {
            if (fds[i].fd < 0 || fds[i].revents == 0) {
                continue;
            }
            int got = append(fds[i].fd, &bufs[i]);
            if (got < 0) {
                failed = errno ? errno : ENOMEM;
            } else if (got == 0) {
                close(fds[i].fd);
                fds[i].fd = -1;
                open_fds--;
            }
        }
    }
    for (int i = 0; i < 2; i++) {
        if (fds[i].fd >= 0) {
            close(fds[i].fd);
        }
    }

    int wstatus;
    while (waitpid(pid, &wstatus, 0) < 0) {
        if (errno != EINTR) {
            failed = failed ? failed : errno;
            break;
        }
    }
    if (!failed) {
        for (int i = 0; i < 2; i++) {
            if (bufs[i].data == nullptr && (bufs[i].data = malloc(1)) == nullptr) {
                failed = ENOMEM;
                break;
            }
            bufs[i].data[bufs[i].len] = '\0';
        }
    }
    if (failed) {
        free(bufs[0].data);
        free(bufs[1].data);
        errno = failed;
        return -1;
    }

    *result = (struct run_result){
        .status = WIFEXITED(wstatus) ? WEXITSTATUS(wstatus) : -1,
        .signal = WIFSIGNALED(wstatus) ? WTERMSIG(wstatus) : 0,
        .out = bufs[0].data,
        .out_len = bufs[0].len,
        .err = bufs[1].data,
        .err_len = bufs[1].len,
    };
    return 0;
}

void run_result_free(struct run_result *result) {
    free(result->out);
    free(result->err);
    result->out = nullptr;
    result->err = nullptr;
}
run.h 29 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/run-a-subprocess/.

#ifndef RUN_H
#define RUN_H

#include <stddef.h>

// The result of a child process. out and err end with a NUL byte that is not
// part of the length. Free them with run_result_free.
struct run_result {
    int status;    // the exit status, 0 to 255, or -1 when signal is not 0
    int signal;    // the signal that stopped the child, or 0
    char *out;     // standard output
    size_t out_len;
    char *err;     // standard error
    size_t err_len;
};

// run starts argv[0] with the arguments argv, which ends with a null pointer.
// It searches PATH for argv[0] and starts no shell. The standard input of the
// child is /dev/null. run reads both output streams to the end, waits for the
// child and returns 0. On an error it returns -1 and sets errno; ENOENT means
// that the program was not found.
int run(char *const argv[], struct run_result *result);

void run_result_free(struct run_result *result);

#endif
test_run.c 116 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/run-a-subprocess/.

#include "run.h"

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct test_case {
    const char *name;
    char *argv[10];
    int status;
    const char *out;
    const char *err;
};

static const struct test_case cases[] = {
    {"hello", {"printf", "hello", nullptr}, 0, "hello", ""},
    {"two-arguments", {"echo", "one", "two", nullptr}, 0, "one two\n", ""},
    {"exit-status", {"sh", "-c", "exit 3", nullptr}, 3, "", ""},
    {"both-streams", {"sh", "-c", "echo out; echo err >&2; exit 2", nullptr}, 2, "out\n", "err\n"},
    {"metacharacters",
     {"printf", "%s|", "a b", "$HOME", "*", "x;y", "\"q\"", "'s'", nullptr},
     0,
     "a b|$HOME|*|x;y|\"q\"|'s'|",
     ""},
    {"empty-argument", {"printf", "[%s]", "", nullptr}, 0, "[]", ""},
    {"newline-argument", {"printf", "%s", "line one\nline two", nullptr}, 0, "line one\nline two", ""},
    {"trailing-newlines", {"printf", "a\\n\\n", nullptr}, 0, "a\n\n", ""},
    {"non-ascii", {"printf", "%s\\n", "xin chào, 日本語, 🙂", nullptr}, 0, "xin chào, 日本語, 🙂\n", ""},
    {"stderr-only", {"sh", "-c", "echo warning >&2", nullptr}, 0, "", "warning\n"},
    {"no-output", {"true", nullptr}, 0, "", ""},
    {"false", {"false", nullptr}, 1, "", ""},
    {"status-255", {"sh", "-c", "exit 255", nullptr}, 255, "", ""},
    {"empty-stdin", {"sh", "-c", "if read -r line; then echo got; else echo eof; fi", nullptr}, 0, "eof\n", ""},
};

static int same(const char *data, size_t len, const char *want) {
    return len == strlen(want) && memcmp(data, want, len) == 0;
}

static int all_bytes(const char *data, size_t len, char c, size_t want) {
    if (len != want) {
        return 0;
    }
    for (size_t i = 0; i < len; i++) {
        if (data[i] != c) {
            return 0;
        }
    }
    return 1;
}

int main(void) {
    int failures = 0;
    for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
        const struct test_case *c = &cases[i];
        struct run_result r;
        if (run(c->argv, &r) != 0) {
            printf("FAIL %s: %s\n", c->name, strerror(errno));
            failures++;
            continue;
        }
        if (r.status != c->status || r.signal != 0 || !same(r.out, r.out_len, c->out) ||
            !same(r.err, r.err_len, c->err)) {
            printf("FAIL %s: status %d, out [%s], err [%s]\n", c->name, r.status, r.out, r.err);
            failures++;
        }
        run_result_free(&r);
    }

    char *large[] = {"sh", "-c",
                     "head -c 1048576 /dev/zero | tr '\\0' x; head -c 1048576 /dev/zero | tr '\\0' y >&2",
                     nullptr};
    struct run_result r;
    if (run(large, &r) != 0) {
        printf("FAIL large-output: %s\n", strerror(errno));
        failures++;
    } else {
        if (r.status != 0 || !all_bytes(r.out, r.out_len, 'x', 1048576) ||
            !all_bytes(r.err, r.err_len, 'y', 1048576)) {
            printf("FAIL large-output: %zu and %zu bytes\n", r.out_len, r.err_len);
            failures++;
        }
        run_result_free(&r);
    }

    char *missing[] = {"no-such-program-7f3a", nullptr};
    if (run(missing, &r) == 0) {
        // POSIX allows posix_spawnp to succeed and the child to exit with 127.
        if (r.status != 127) {
            printf("FAIL missing-program: status %d\n", r.status);
            failures++;
        }
        run_result_free(&r);
    } else if (errno != ENOENT) {
        printf("FAIL missing-program: %s\n", strerror(errno));
        failures++;
    }

    char *killed[] = {"sh", "-c", "kill -9 $$", nullptr};
    if (run(killed, &r) != 0 || r.status != -1 || r.signal != 9) {
        printf("FAIL signal\n");
        failures++;
    } else {
        run_result_free(&r);
    }

    if (failures > 0) {
        return 1;
    }
    puts("all cases pass");
    return 0;
}
RunProcess.csI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/run-a-subprocess/.

using System.Diagnostics;
using System.Text;

public static class RunProcess
{
    /// <summary>
    /// Runs argv with no shell and returns the exit status and the text of
    /// the two output streams. A missing program throws a Win32Exception.
    /// </summary>
    public static (int Status, string Stdout, string Stderr) Run(IReadOnlyList<string> argv)
    {
        var info = new ProcessStartInfo(argv[0])
        {
            UseShellExecute = false,
            RedirectStandardInput = true,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            StandardOutputEncoding = Encoding.UTF8,
            StandardErrorEncoding = Encoding.UTF8,
        };
        // ArgumentList passes each element as one argument, with no quoting.
        foreach (var arg in argv.Skip(1))
        {
            info.ArgumentList.Add(arg);
        }
        using var process = new Process { StartInfo = info };
        process.Start();
        // Close the standard input of the child, so a read gets end of file.
        process.StandardInput.Close();
        // Read standard error asynchronously while this thread reads
        // standard output. Two synchronous reads can deadlock.
        var stderr = process.StandardError.ReadToEndAsync();
        var stdout = process.StandardOutput.ReadToEnd();
        process.WaitForExit();
        return (process.ExitCode, stdout, stderr.GetAwaiter().GetResult());
    }
}
RunProcessTests.cs 49 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/run-a-subprocess/.

using System.ComponentModel;
using Xunit;

public sealed class RunProcessTests
{
    public static TheoryData<string, string[], int, string, string> Cases => new()
    {
        { "hello", ["printf", "hello"], 0, "hello", "" },
        { "two-arguments", ["echo", "one", "two"], 0, "one two\n", "" },
        { "exit-status", ["sh", "-c", "exit 3"], 3, "", "" },
        { "both-streams", ["sh", "-c", "echo out; echo err >&2; exit 2"], 2, "out\n", "err\n" },
        { "metacharacters", ["printf", "%s|", "a b", "$HOME", "*", "x;y", "\"q\"", "'s'"], 0, "a b|$HOME|*|x;y|\"q\"|'s'|", "" },
        { "empty-argument", ["printf", "[%s]", ""], 0, "[]", "" },
        { "newline-argument", ["printf", "%s", "line one\nline two"], 0, "line one\nline two", "" },
        { "trailing-newlines", ["printf", "a\\n\\n"], 0, "a\n\n", "" },
        { "non-ascii", ["printf", "%s\\n", "xin chào, 日本語, 🙂"], 0, "xin chào, 日本語, 🙂\n", "" },
        { "stderr-only", ["sh", "-c", "echo warning >&2"], 0, "", "warning\n" },
        { "no-output", ["true"], 0, "", "" },
        { "false", ["false"], 1, "", "" },
        { "status-255", ["sh", "-c", "exit 255"], 255, "", "" },
        { "empty-stdin", ["sh", "-c", "if read -r line; then echo got; else echo eof; fi"], 0, "eof\n", "" },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void RunsTheProgram(string label, string[] argv, int status, string stdout, string stderr)
    {
        Assert.True((status, stdout, stderr) == RunProcess.Run(argv), label);
    }

    [Fact]
    public void LargeOutputOnBothStreams()
    {
        var script = "head -c 1048576 /dev/zero | tr '\\0' x; head -c 1048576 /dev/zero | tr '\\0' y >&2";
        var (status, stdout, stderr) = RunProcess.Run(["sh", "-c", script]);
        Assert.Equal(0, status);
        Assert.Equal(new string('x', 1048576), stdout);
        Assert.Equal(new string('y', 1048576), stderr);
    }

    [Fact]
    public void MissingProgram()
    {
        Assert.Throws<Win32Exception>(() => RunProcess.Run(["no-such-program-7f3a"]));
    }
}
run.jsI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/run-a-subprocess/.

import { spawnSync } from "node:child_process";

/**
 * Runs argv with no shell and returns [status, stdout, stderr].
 * A missing program throws an Error with the code "ENOENT".
 * @param {string[]} argv
 * @returns {[number, string, string]}
 */
export function run(argv) {
  const [file, ...args] = argv;
  const result = spawnSync(file, args, {
    stdio: ["ignore", "pipe", "pipe"],
    encoding: "utf8",
    // The default limit is 1 MiB on each stream. Past it, Node.js stops
    // the child and cuts the output.
    maxBuffer: Infinity,
  });
  if (result.error) {
    throw result.error;
  }
  if (result.status === null) {
    throw new Error(`${file} was stopped by signal ${result.signal}`);
  }
  return [result.status, result.stdout, result.stderr];
}
run.test.js 47 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/run-a-subprocess/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { run } from "./run.js";

// [case, argv, expected [status, stdout, stderr]]
const cases = [
  ["hello", ["printf", "hello"], [0, "hello", ""]],
  ["two-arguments", ["echo", "one", "two"], [0, "one two\n", ""]],
  ["exit-status", ["sh", "-c", "exit 3"], [3, "", ""]],
  ["both-streams", ["sh", "-c", "echo out; echo err >&2; exit 2"], [2, "out\n", "err\n"]],
  ["metacharacters", ["printf", "%s|", "a b", "$HOME", "*", "x;y", '"q"', "'s'"], [0, "a b|$HOME|*|x;y|\"q\"|'s'|", ""]],
  ["empty-argument", ["printf", "[%s]", ""], [0, "[]", ""]],
  ["newline-argument", ["printf", "%s", "line one\nline two"], [0, "line one\nline two", ""]],
  ["trailing-newlines", ["printf", "a\\n\\n"], [0, "a\n\n", ""]],
  ["non-ascii", ["printf", "%s\\n", "xin chào, 日本語, 🙂"], [0, "xin chào, 日本語, 🙂\n", ""]],
  ["stderr-only", ["sh", "-c", "echo warning >&2"], [0, "", "warning\n"]],
  ["no-output", ["true"], [0, "", ""]],
  ["false", ["false"], [1, "", ""]],
  ["status-255", ["sh", "-c", "exit 255"], [255, "", ""]],
  ["empty-stdin", ["sh", "-c", "if read -r line; then echo got; else echo eof; fi"], [0, "eof\n", ""]],
];

for (const [name, argv, want] of cases) {
  test(name, () => {
    assert.deepEqual(run(argv), want);
  });
}

test("large output on both streams", () => {
  const script = "head -c 1048576 /dev/zero | tr '\\0' x; head -c 1048576 /dev/zero | tr '\\0' y >&2";
  const [status, out, err] = run(["sh", "-c", script]);
  assert.equal(status, 0);
  assert.equal(out, "x".repeat(1048576));
  assert.equal(err, "y".repeat(1048576));
});

test("missing program", () => {
  assert.throws(() => run(["no-such-program-7f3a"]), { code: "ENOENT" });
});

test("signal", () => {
  assert.throws(() => run(["sh", "-c", "kill -9 $$"]), /signal SIGKILL/);
});
run.tsI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/run-a-subprocess/.

import { spawnSync } from "node:child_process";

/**
 * Runs argv with no shell and returns [status, stdout, stderr].
 * A missing program throws an Error with the code "ENOENT".
 */
export function run(argv: readonly string[]): [number, string, string] {
  const [file, ...args] = argv;
  if (file === undefined) {
    throw new RangeError("argv is empty");
  }
  const result = spawnSync(file, args, {
    stdio: ["ignore", "pipe", "pipe"],
    encoding: "utf8",
    // The default limit is 1 MiB on each stream. Past it, Node.js stops
    // the child and cuts the output.
    maxBuffer: Infinity,
  });
  if (result.error) {
    throw result.error;
  }
  if (result.status === null) {
    throw new Error(`${file} was stopped by signal ${result.signal}`);
  }
  return [result.status, result.stdout, result.stderr];
}
run.test.ts 47 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/run-a-subprocess/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { run } from "./run.ts";

// [case, argv, expected [status, stdout, stderr]]
const cases = [
  ["hello", ["printf", "hello"], [0, "hello", ""]],
  ["two-arguments", ["echo", "one", "two"], [0, "one two\n", ""]],
  ["exit-status", ["sh", "-c", "exit 3"], [3, "", ""]],
  ["both-streams", ["sh", "-c", "echo out; echo err >&2; exit 2"], [2, "out\n", "err\n"]],
  ["metacharacters", ["printf", "%s|", "a b", "$HOME", "*", "x;y", '"q"', "'s'"], [0, "a b|$HOME|*|x;y|\"q\"|'s'|", ""]],
  ["empty-argument", ["printf", "[%s]", ""], [0, "[]", ""]],
  ["newline-argument", ["printf", "%s", "line one\nline two"], [0, "line one\nline two", ""]],
  ["trailing-newlines", ["printf", "a\\n\\n"], [0, "a\n\n", ""]],
  ["non-ascii", ["printf", "%s\\n", "xin chào, 日本語, 🙂"], [0, "xin chào, 日本語, 🙂\n", ""]],
  ["stderr-only", ["sh", "-c", "echo warning >&2"], [0, "", "warning\n"]],
  ["no-output", ["true"], [0, "", ""]],
  ["false", ["false"], [1, "", ""]],
  ["status-255", ["sh", "-c", "exit 255"], [255, "", ""]],
  ["empty-stdin", ["sh", "-c", "if read -r line; then echo got; else echo eof; fi"], [0, "eof\n", ""]],
];

for (const [name, argv, want] of cases) {
  test(name, () => {
    assert.deepEqual(run(argv), want);
  });
}

test("large output on both streams", () => {
  const script = "head -c 1048576 /dev/zero | tr '\\0' x; head -c 1048576 /dev/zero | tr '\\0' y >&2";
  const [status, out, err] = run(["sh", "-c", script]);
  assert.equal(status, 0);
  assert.equal(out, "x".repeat(1048576));
  assert.equal(err, "y".repeat(1048576));
});

test("missing program", () => {
  assert.throws(() => run(["no-such-program-7f3a"]), { code: "ENOENT" });
});

test("signal", () => {
  assert.throws(() => run(["sh", "-c", "kill -9 $$"]), /signal SIGKILL/);
});
run.goI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/run-a-subprocess/.

// Package run runs a program with an argument list and no shell.
package run

import (
	"errors"
	"fmt"
	"os/exec"
	"strings"
)

// Run runs argv and returns the exit status and the text of the two output
// streams. A missing program gives an error that wraps exec.ErrNotFound. A
// status that is not 0 is a result, not an error.
func Run(argv []string) (int, string, string, error) {
	cmd := exec.Command(argv[0], argv[1:]...)
	// A nil Stdin reads from os.DevNull. Two writers that are not files make
	// the package copy each pipe on its own goroutine, so no pipe fills.
	var stdout, stderr strings.Builder
	cmd.Stdout = &stdout
	cmd.Stderr = &stderr
	err := cmd.Run()
	var exitErr *exec.ExitError
	if err != nil && !errors.As(err, &exitErr) {
		return 0, "", "", err
	}
	status := cmd.ProcessState.ExitCode()
	if status == -1 {
		return 0, "", "", fmt.Errorf("%s: %s", argv[0], cmd.ProcessState)
	}
	return status, stdout.String(), stderr.String(), nil
}
run_test.go 71 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/run-a-subprocess/.

package run

import (
	"errors"
	"os/exec"
	"strings"
	"testing"
)

func TestCases(t *testing.T) {
	cases := []struct {
		name           string
		argv           []string
		status         int
		stdout, stderr string
	}{
		{"hello", []string{"printf", "hello"}, 0, "hello", ""},
		{"two-arguments", []string{"echo", "one", "two"}, 0, "one two\n", ""},
		{"exit-status", []string{"sh", "-c", "exit 3"}, 3, "", ""},
		{"both-streams", []string{"sh", "-c", "echo out; echo err >&2; exit 2"}, 2, "out\n", "err\n"},
		{"metacharacters", []string{"printf", "%s|", "a b", "$HOME", "*", "x;y", `"q"`, "'s'"}, 0, `a b|$HOME|*|x;y|"q"|'s'|`, ""},
		{"empty-argument", []string{"printf", "[%s]", ""}, 0, "[]", ""},
		{"newline-argument", []string{"printf", "%s", "line one\nline two"}, 0, "line one\nline two", ""},
		{"trailing-newlines", []string{"printf", `a\n\n`}, 0, "a\n\n", ""},
		{"non-ascii", []string{"printf", `%s\n`, "xin chào, 日本語, 🙂"}, 0, "xin chào, 日本語, 🙂\n", ""},
		{"stderr-only", []string{"sh", "-c", "echo warning >&2"}, 0, "", "warning\n"},
		{"no-output", []string{"true"}, 0, "", ""},
		{"false", []string{"false"}, 1, "", ""},
		{"status-255", []string{"sh", "-c", "exit 255"}, 255, "", ""},
		{"empty-stdin", []string{"sh", "-c", "if read -r line; then echo got; else echo eof; fi"}, 0, "eof\n", ""},
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			status, stdout, stderr, err := Run(c.argv)
			if err != nil {
				t.Fatalf("Run(%q): %v", c.argv, err)
			}
			if status != c.status || stdout != c.stdout || stderr != c.stderr {
				t.Errorf("Run(%q) = %d, %q, %q; want %d, %q, %q", c.argv, status, stdout, stderr, c.status, c.stdout, c.stderr)
			}
		})
	}
}

func TestLargeOutputOnBothStreams(t *testing.T) {
	script := `head -c 1048576 /dev/zero | tr '\0' x; head -c 1048576 /dev/zero | tr '\0' y >&2`
	status, stdout, stderr, err := Run([]string{"sh", "-c", script})
	if err != nil || status != 0 {
		t.Fatalf("Run: %d, %v", status, err)
	}
	if stdout != strings.Repeat("x", 1048576) || stderr != strings.Repeat("y", 1048576) {
		t.Errorf("Run: got %d and %d bytes", len(stdout), len(stderr))
	}
}

func TestMissingProgram(t *testing.T) {
	_, _, _, err := Run([]string{"no-such-program-7f3a"})
	if !errors.Is(err, exec.ErrNotFound) {
		t.Errorf("Run: err = %v; want exec.ErrNotFound", err)
	}
}

func TestSignal(t *testing.T) {
	_, _, _, err := Run([]string{"sh", "-c", "kill -9 $$"})
	if err == nil {
		t.Errorf("Run: no error for a child that a signal stopped")
	}
}
run.rsI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/run-a-subprocess/.

use std::io;
use std::process::Command;

/// Runs `argv` with no shell and returns the exit status and the text of the
/// two output streams. A missing program gives an error of the kind
/// `NotFound`. A status that is not 0 is a result, not an error.
pub fn run(argv: &[&str]) -> io::Result<(i32, String, String)> {
    let (program, args) = argv
        .split_first()
        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "argv is empty"))?;
    // output() reads both pipes to the end and waits for the child. The
    // standard input of the child is closed at once.
    let output = Command::new(program).args(args).output()?;
    // On Unix, code() is None when a signal stopped the child.
    let status = output
        .status
        .code()
        .ok_or_else(|| io::Error::other(format!("{program}: {}", output.status)))?;
    let text = |bytes: Vec<u8>| {
        String::from_utf8(bytes).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
    };
    Ok((status, text(output.stdout)?, text(output.stderr)?))
}
tests/run_test.rs 84 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/run-a-subprocess/.

use std::io::ErrorKind;

use algo_run_a_subprocess::run;

#[test]
fn cases() {
    let cases: [(&str, &[&str], i32, &str, &str); 14] = [
        ("hello", &["printf", "hello"], 0, "hello", ""),
        ("two-arguments", &["echo", "one", "two"], 0, "one two\n", ""),
        ("exit-status", &["sh", "-c", "exit 3"], 3, "", ""),
        (
            "both-streams",
            &["sh", "-c", "echo out; echo err >&2; exit 2"],
            2,
            "out\n",
            "err\n",
        ),
        (
            "metacharacters",
            &["printf", "%s|", "a b", "$HOME", "*", "x;y", "\"q\"", "'s'"],
            0,
            "a b|$HOME|*|x;y|\"q\"|'s'|",
            "",
        ),
        ("empty-argument", &["printf", "[%s]", ""], 0, "[]", ""),
        (
            "newline-argument",
            &["printf", "%s", "line one\nline two"],
            0,
            "line one\nline two",
            "",
        ),
        ("trailing-newlines", &["printf", r"a\n\n"], 0, "a\n\n", ""),
        (
            "non-ascii",
            &["printf", r"%s\n", "xin chào, 日本語, 🙂"],
            0,
            "xin chào, 日本語, 🙂\n",
            "",
        ),
        ("stderr-only", &["sh", "-c", "echo warning >&2"], 0, "", "warning\n"),
        ("no-output", &["true"], 0, "", ""),
        ("false", &["false"], 1, "", ""),
        ("status-255", &["sh", "-c", "exit 255"], 255, "", ""),
        (
            "empty-stdin",
            &["sh", "-c", "if read -r line; then echo got; else echo eof; fi"],
            0,
            "eof\n",
            "",
        ),
    ];
    for (name, argv, status, stdout, stderr) in cases {
        let got = run(argv).unwrap_or_else(|e| panic!("{name}: {e}"));
        assert_eq!(
            got,
            (status, stdout.to_string(), stderr.to_string()),
            "{name}"
        );
    }
}

#[test]
fn large_output_on_both_streams() {
    let script = r"head -c 1048576 /dev/zero | tr '\0' x; head -c 1048576 /dev/zero | tr '\0' y >&2";
    let (status, stdout, stderr) = run(&["sh", "-c", script]).unwrap();
    assert_eq!(status, 0);
    assert_eq!(stdout, "x".repeat(1048576));
    assert_eq!(stderr, "y".repeat(1048576));
}

#[test]
fn missing_program() {
    let err = run(&["no-such-program-7f3a"]).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::NotFound);
}

#[test]
fn signal() {
    assert!(run(&["sh", "-c", "kill -9 $$"]).is_err());
}
run.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/run-a-subprocess/.

# run_program STATUS_VAR OUT_VAR ERR_VAR PROGRAM [ARG...]
# Runs PROGRAM with the arguments and stores its exit status, its standard
# output and its standard error in the three variables. It returns 0, or 1
# with a message on standard error when PROGRAM is not found.
run_program() {
  local __status_var=$1 __out_var=$2 __err_var=$3 __path __dir __status __out __err
  shift 3
  # type -P searches PATH for a file. It skips functions and builtins, so
  # "printf" runs /usr/bin/printf and not the builtin.
  if ! __path=$(type -P -- "$1"); then
    printf 'run_program: %s: not found\n' "$1" >&2
    return 1
  fi
  __dir=$(mktemp -d) || return 1
  # The || keeps a status that is not 0 from stopping a caller with set -e.
  __status=0
  "$__path" "${@:2}" </dev/null >"$__dir/out" 2>"$__dir/err" || __status=$?
  # $(...) deletes trailing newlines, so add a character and remove it.
  __out=$(cat "$__dir/out" && printf x) && __out=${__out%x}
  __err=$(cat "$__dir/err" && printf x) && __err=${__err%x}
  rm -rf "$__dir"
  printf -v "$__status_var" '%s' "$__status"
  printf -v "$__out_var" '%s' "$__out"
  printf -v "$__err_var" '%s' "$__err"
}
test_run.bats 50 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/run-a-subprocess/.

bats_require_minimum_version 1.5.0

setup() {
  source "$BATS_TEST_DIRNAME/run.sh"
}

check() { # check STATUS OUT ERR PROGRAM [ARG...]
  local want_status=$1 want_out=$2 want_err=$3 status out err
  shift 3
  run_program status out err "$@"
  [ "$status" = "$want_status" ]
  [ "$out" = "$want_out" ]
  [ "$err" = "$want_err" ]
}

nl=$'\n'

@test "hello" { check 0 "hello" "" printf hello; }
@test "two-arguments" { check 0 "one two$nl" "" echo one two; }
@test "exit-status" { check 3 "" "" sh -c 'exit 3'; }
@test "both-streams" { check 2 "out$nl" "err$nl" sh -c 'echo out; echo err >&2; exit 2'; }
@test "metacharacters" { check 0 "a b|\$HOME|*|x;y|\"q\"|'s'|" "" printf '%s|' 'a b' '$HOME' '*' 'x;y' '"q"' "'s'"; }
@test "empty-argument" { check 0 "[]" "" printf '[%s]' ''; }
@test "newline-argument" { check 0 "line one${nl}line two" "" printf '%s' "line one${nl}line two"; }
@test "trailing-newlines" { check 0 "a$nl$nl" "" printf 'a\n\n'; }
@test "non-ascii" { check 0 "xin chào, 日本語, 🙂$nl" "" printf '%s\n' 'xin chào, 日本語, 🙂'; }
@test "stderr-only" { check 0 "" "warning$nl" sh -c 'echo warning >&2'; }
@test "no-output" { check 0 "" "" true; }
@test "false" { check 1 "" "" false; }
@test "status-255" { check 255 "" "" sh -c 'exit 255'; }
@test "empty-stdin" { check 0 "eof$nl" "" sh -c 'if read -r line; then echo got; else echo eof; fi'; }

@test "large-output-on-both-streams" {
  local status out err
  run_program status out err sh -c "head -c 1048576 /dev/zero | tr '\\0' x; head -c 1048576 /dev/zero | tr '\\0' y >&2"
  [ "$status" -eq 0 ]
  [ "$out" = "$(head -c 1048576 /dev/zero | tr '\0' x)" ]
  [ "$err" = "$(head -c 1048576 /dev/zero | tr '\0' y)" ]
}

@test "missing-program" {
  run --separate-stderr run_program s o e no-such-program-7f3a
  [ "$status" -eq 1 ]
  [ -z "$output" ]
  [ -n "$stderr" ]
}

References

  1. The Open Group, POSIX.1-2024, posix_spawn, posix_spawnp, Description, Errors
  2. The Open Group, POSIX.1-2024, wait, waitpid, Description, WIFEXITED, WEXITSTATUS, WIFSIGNALED, WTERMSIG
  3. The Open Group, POSIX.1-2024, Shell Command Language, 2.6.3 Command Substitution, 2.8.2 Exit Status for Commands
  4. The Python Standard Library, subprocess, Subprocess management, subprocess.run, subprocess.DEVNULL, Exceptions, Popen.wait, Popen.returncode, Security Considerations
  5. The Python Standard Library, Built-in Exceptions, OS exceptions, FileNotFoundError
  6. Node.js documentation, Child process, child_process.spawnSync, options.stdio, child_process.spawn, child_process.exec, child_process.execFile
  7. Java SE 25 API, java.lang.Process, class description, getOutputStream, waitFor
  8. Java SE 25 API, java.lang.ProcessBuilder, class description, start, environment, directory
  9. .NET API reference, ProcessStartInfo.ArgumentList, Remarks
  10. .NET API reference, Process.StandardOutput, Remarks
  11. .NET API reference, Process.Start, Start(ProcessStartInfo), Exceptions
  12. Go standard library, package os/exec, Overview, Command, Cmd, Cmd.Run, ErrNotFound, ExitError
  13. Go standard library, package os, ProcessState.ExitCode
  14. The Rust Standard Library, std::process::Command, new, arg, output, spawn
  15. The Rust Standard Library, std::process::ExitStatus, code
  16. GNU Bash Reference Manual, Exit Status, 3.7.5
  17. GNU Bash Reference Manual, Bash Builtin Commands, 4.2, type

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (cpp)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (csharp)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (go)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (java)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (javascript)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (python)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (rust)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (typescript)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source

The native tests pass in 9 of 10 languages in this build.