Child processes

A Go application can interact with the operating system to create some other processes. Another subpackage of os offers the functionality to create and run new processes. Inside the os/exec package, there is the Cmd type, which represents command execution:

type Cmd struct {
Path string // command to run.
Args []string // command line arguments (including command)
Env []string // environment of the process
Dir string // working directory
Stdin io.Reader // standard input`
Stdout io.Writer // standard output
Stderr io.Writer // standard error
ExtraFiles []*os.File // additional open files
SysProcAttr *syscall.SysProcAttr // os specific attributes
Process *os.Process // underlying process
ProcessState *os.ProcessState // information on exited processte
}

The easiest way to create a new command is by using the exec.Command function, which takes the executable path and a series of arguments. Let's look at a simple example with an echo command and some arguments:

package main

import (
"fmt"
"os/exec"
)

func main() {
cmd := exec.Command("echo", "A", "sample", "command")
fmt.Println(cmd.Path, cmd.Args[1:]) // echo [A sample command]
}

The full example is available at https://play.golang.org/p/dBIAUteJbxI.

One very important detail is the nature of standard input, output, and error – they are all interfaces that we are already familiar with:

  • The input is an io.Readerwhich could be bytes.Reader, bytes.Buffer, strings.Reader, os.Fileor any other implementation.
  • The output and the error are io.Writer, can also be os.File or bytes.Buffer, and can also be strings.Builder or any another writer implementation.

There are different ways to launch the process, depending on what the parent application needs:

  • Cmd.Run: Executes the command, and returns an error that is nil if the child process is executed correctly.
  • Cmd.Start : Executes the command asynchronously and lets the parent continue its flow. In order to wait for the child process to finish its execution, there is another method, Cmd.Wait.
  • Cmd.Output: Executes the command and returns its standard output, and returns an error if Stderr isn't defined but the standard error produced the output.
  • Cmd.CombinedOutput: Executes the command and returns both a standard error and output combined, which is very useful when the entire output of the child process-standard output plus standard error needs to be checked or saved.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.68.18