ruk·si

🐹 Go
Process Management

Updated at 2022-01-17 22:34

Running a command.

package main

import (
    "os/exec"
)

func assert(condition bool) {
    if !condition {
        panic("assert failed")
    }
}

func main() {
    cmd := exec.Command("echo", "-n", "hello", "there")
    output, err := cmd.Output()
    assert(err == nil)
    assert(string(output) == "hello there")
}

Starting a command then interacting with it while it runs.

package main

import (
    "io/ioutil"
    "os/exec"
)

func assert(condition bool) {
    if !condition {
        panic("assert failed")
    }
}

func main() {
    cmd := exec.Command("grep", "ello")
    stdin, err := cmd.StdinPipe()
    assert(err == nil)
    stdout, err := cmd.StdoutPipe()
    assert(err == nil)
    stderr, err := cmd.StderrPipe()
    assert(err == nil)

    // starts the command but does not wait for it to finish
    err = cmd.Start()
    assert(err == nil)

    // giving input to the command
    _, err = stdin.Write([]byte("hello grep\ngoodbye grep\njello"))
    assert(err == nil)
    // closing the input pipe so the command knows it can start
    err = stdin.Close()
    assert(err == nil)

    // read everything from the `stdout` and `stderr`
    output, err := ioutil.ReadAll(stdout)
    assert(err == nil)
    errors, err := ioutil.ReadAll(stderr)
    assert(err == nil)

    // waits the command to exit, must be after `Start()`
    err = cmd.Wait()
    assert(err == nil)

    assert(string(output) == "hello grep\njello\n")
    assert(string(errors) == "")
    assert(cmd.ProcessState.Exited())
    assert(cmd.ProcessState.ExitCode() == 0)
}

Sources