process

    A module for spawning and managing system processes.

    native-only
    process
    system
    Download zip
    Author
    Version
    0.1.0
    License
    Apache-2.0
    Last updated
    7 months ago
    Downloads
    30

    #Process Library for MoonBit

    This library provides facilities for managing external processes, similar to std::process::Command in Rust or os/exec in Go.

    #Features

    • Command Construction: Builder pattern for configuring command, arguments, environment, and working directory.
    • I/O Redirection: Support for piping stdin, stdout, and stderr (Inherit, Piped, Null).
    • Process Management:
      • spawn() for non-blocking execution yielding a Child handle.
      • Child handle supports:
        • pid(): Access the process ID.
        • wait(): Wait for completion.
        • kill(): Terminate the process.
        • write_stdin(), read_stdout(), read_stderr(), close_stdin(): Manual I/O interaction.
    • Convenience: output() method to capture all stdout/stderr and exit status.

    #Usage

    #Simple Output Capture

    test {
    // Example: Running a simple command and capturing output
    let output = try {
    Command::new("moon")
    .arg("version")
    .stdout(Piped) // Capture stdout
    .output()
    } catch {
    e => abort("Failed to execute process: \{e}")
    }

    if output.status.success() {
    println("Command succeeded!")
    // Access output.stdout
    }
    }

    #Manual Pipe Interaction

    test {
    // Example: Writing to stdin and reading from stdout
    // Note: "grep" needs to be available in your PATH (use "findstr" on Windows)
    let child = Command::new("grep")
    .arg("hello")
    .stdin(Piped)
    .stdout(Piped)
    .spawn()
    // Write to stdin
    let input = @utf8.encode("hello world\ngoodbye\n")
    let _ = child.write_stdin(input)
    child.close_stdin() // Signal EOF

    // Read from stdout
    let buf = Bytes::make(1024, b'\x00')
    let n = child.read_stdout(buf)
    if n > 0 {
    let _out_str = @utf8.decode(buf) // "hello world\n"
    ()
    }

    let _ = child.wait()
    }

    #Platform Compatibility

    This library is primarily designed for native compilation targets (Linux, macOS, Windows).

    #WASM Limitations

    In WebAssembly environments (WASM/WASI), the capability to spawn external subprocesses is typically restricted or non-existent. Attempting to use spawn or output in a WASM environment may result in runtime errors or traps.

    #API Overview

    • Command: The main entry point.
    • Stdio: Configuration for input/output streams.
    • Child: Handle to a running process.
    • ExitStatus: Status code of a terminated process.

    ProcessError

    pub suberror ProcessError {
    NotFound(String)
    PermissionDenied(String)
    Unknown(String)
    }

    impl Eq for ProcessError

    Child

    pub(all) struct Child {
    pid : Int
    handle : Int64
    stdin : Int64
    stdout : Int64
    stderr : Int64
    }

    A handle to a child process.

    Child::close_stdin

    fn Child::close_stdin(self : Child) -> Unit

    Closes the child process's standard input. This is useful to signal EOF to the child process.

    Child::kill

    fn Child::kill(self : Child) -> Unit raise ProcessError

    Forces the child process to exit.

    This sends a distinct kill signal (e.g., SIGKILL on Unix, TerminateProcess on Windows) to the child process.

    Child::pid

    fn Child::pid(self : Child) -> Int

    Returns the process ID of the child process.

    Child::read_stderr

    fn Child::read_stderr(self : Child, buf : Bytes) -> Int

    Reads data from the child process's standard error into the provided buffer. Returns the number of bytes read.

    Note: The child process must have been spawned with stderr(Piped).

    Child::read_stdout

    fn Child::read_stdout(self : Child, buf : Bytes) -> Int

    Reads data from the child process's standard output into the provided buffer. Returns the number of bytes read.

    Note: The child process must have been spawned with stdout(Piped).

    Child::wait

    fn Child::wait(self : Child) -> ExitStatus raise ProcessError

    Waits for the child process to exit and returns its exit status.

    This function will block the current thread until the child has terminated.

    Child::write_stdin

    fn Child::write_stdin(self : Child, data : Bytes) -> Int

    Writes data to the child process's standard input. Returns the number of bytes written.

    Note: The child process must have been spawned with stdin(Piped). If stdin is not piped, this function may return an error or 0.

    Command

    pub struct Command {
    program : String
    args : Array[String]
    env_clear : Bool
    env_vars : Map[String, String]
    cwd : String?
    stdin : Stdio
    stdout : Stdio
    stderr : Stdio
    }

    A builder for creating and configuring a new process. This structure mimics the Rust std::process::Command API.

    Command::arg

    fn Command::arg(self : Command, arg : String) -> Command

    Appends an argument to the command.

    Command::args

    fn Command::args(self : Command, args : Array[String]) -> Command

    Appends multiple arguments to the command.

    Command::current_dir

    fn Command::current_dir(self : Command, dir : String) -> Command

    Sets the working directory for the new process.

    Command::env

    fn Command::env(self : Command, key : String, value : String) -> Command

    Configures an environment variable for the new process.

    Note: By default, the new process inherits the environment of the parent process. Use env_clear to prevent this.

    Command::env_clear

    fn Command::env_clear(self : Command) -> Command

    Clears all environment variables for the new process. If this is called, the child process will start with no environment variables (except those explicitly added via env).

    Command::env_remove

    fn Command::env_remove(self : Command, key : String) -> Command

    Removes an environment variable from the configuration.

    Command::new

    fn Command::new(program : String) -> Command

    Creates a new Command for the given program.

    Arguments

    • program - The path to the program to execute.

    Command::output

    fn Command::output(self : Command) -> Output raise ProcessError

    Executes the command as a child process, waiting for it to finish and collecting all of its output.

    This will implicitly set stdout and stderr to Piped if they are not already configured.

    Command::spawn

    fn Command::spawn(self : Command) -> Child raise ProcessError

    Executes the command as a child process, returning a handle to it.

    Platform Compatibility

    This function is intended for native targets (Linux, macOS, Windows).

    WASM Limitations

    In a WASM environment (e.g., standard WASM or WASI), spawning arbitrary external processes is typically restricted or unsupported. Calling this method in such environments may trap or return a generic error.

    Command::stderr

    fn Command::stderr(self : Command, cfg : Stdio) -> Command

    Configures the standard error (stderr) for the new process.

    Command::stdin

    fn Command::stdin(self : Command, cfg : Stdio) -> Command

    Configures the standard input (stdin) for the new process.

    Command::stdout

    fn Command::stdout(self : Command, cfg : Stdio) -> Command

    Configures the standard output (stdout) for the new process.

    ExitStatus

    pub struct ExitStatus {
    exit_code : Int
    }

    Describes the result of a process execution.
    impl Eq for ExitStatus
    impl Show for ExitStatus

    ExitStatus::code

    fn ExitStatus::code(self : ExitStatus) -> Int

    Returns the exit code of the process.

    ExitStatus::success

    fn ExitStatus::success(self : ExitStatus) -> Bool

    Returns true if the process exited successfully (exit code 0).

    Output

    pub struct Output {
    status : ExitStatus
    stdout : Bytes
    stderr : Bytes
    }

    Represents the output of a finished process.
    impl Eq for Output
    impl Show for Output

    Stdio

    pub(all) enum Stdio {
    Inherit
    Piped
    Null
    }

    Represents a configuration for a standard stream (stdin, stdout, stderr).
    impl Eq for Stdio
    impl Show for Stdio

    Source Files

    Powered by MoonBit

    Site sourceReport issuePackagesBuild queueSkillsStatistics

    © 2026 mooncakes.io