1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // Package exec runs external commands. It wraps os.StartProcess to make it
6 // easier to remap stdin and stdout, connect I/O with pipes, and do other
19 // Error records the name of a binary that failed to be be executed
20 // and the reason it failed.
26 func (e *Error) Error() string {
27 return "exec: " + strconv.Quote(e.Name) + ": " + e.Err.Error()
30 // Cmd represents an external command being prepared or run.
32 // Path is the path of the command to run.
34 // This is the only field that must be set to a non-zero
38 // Args holds command line arguments, including the command as Args[0].
39 // If the Args field is empty or nil, Run uses {Path}.
41 // In typical use, both Path and Args are set by calling Command.
44 // Env specifies the environment of the process.
45 // If Env is nil, Run uses the current process's environment.
48 // Dir specifies the working directory of the command.
49 // If Dir is the empty string, Run runs the command in the
50 // calling process's current directory.
53 // Stdin specifies the process's standard input. If Stdin is
54 // nil, the process reads from the null device (os.DevNull).
57 // Stdout and Stderr specify the process's standard output and error.
59 // If either is nil, Run connects the corresponding file descriptor
60 // to the null device (os.DevNull).
62 // If Stdout and Stderr are the same writer, at most one
63 // goroutine at a time will call Write.
67 // ExtraFiles specifies additional open files to be inherited by the
68 // new process. It does not include standard input, standard output, or
69 // standard error. If non-nil, entry i becomes file descriptor 3+i.
71 // BUG: on OS X 10.6, child processes may sometimes inherit unwanted fds.
72 // http://golang.org/issue/2603
75 // SysProcAttr holds optional, operating system-specific attributes.
76 // Run passes it to os.StartProcess as the os.ProcAttr's Sys field.
77 SysProcAttr *syscall.SysProcAttr
79 // Process is the underlying process, once started.
82 // ProcessState contains information about an exited process,
83 // available after a call to Wait or Run.
84 ProcessState *os.ProcessState
86 err error // last error (from LookPath, stdin, stdout, stderr)
87 finished bool // when Wait was called
89 closeAfterStart []io.Closer
90 closeAfterWait []io.Closer
91 goroutine []func() error
92 errch chan error // one send per goroutine
95 // Command returns the Cmd struct to execute the named program with
96 // the given arguments.
98 // It sets Path and Args in the returned structure and zeroes the
101 // If name contains no path separators, Command uses LookPath to
102 // resolve the path to a complete name if possible. Otherwise it uses
105 // The returned Cmd's Args field is constructed from the command name
106 // followed by the elements of arg, so arg should not include the
107 // command name itself. For example, Command("echo", "hello")
108 func Command(name string, arg ...string) *Cmd {
109 aname, err := LookPath(name)
115 Args: append([]string{name}, arg...),
120 // interfaceEqual protects against panics from doing equality tests on
121 // two interfaces with non-comparable underlying types
122 func interfaceEqual(a, b interface{}) bool {
129 func (c *Cmd) envv() []string {
136 func (c *Cmd) argv() []string {
140 return []string{c.Path}
143 func (c *Cmd) stdin() (f *os.File, err error) {
145 f, err = os.Open(os.DevNull)
146 c.closeAfterStart = append(c.closeAfterStart, f)
150 if f, ok := c.Stdin.(*os.File); ok {
154 pr, pw, err := os.Pipe()
159 c.closeAfterStart = append(c.closeAfterStart, pr)
160 c.closeAfterWait = append(c.closeAfterWait, pw)
161 c.goroutine = append(c.goroutine, func() error {
162 _, err := io.Copy(pw, c.Stdin)
163 if err1 := pw.Close(); err == nil {
171 func (c *Cmd) stdout() (f *os.File, err error) {
172 return c.writerDescriptor(c.Stdout)
175 func (c *Cmd) stderr() (f *os.File, err error) {
176 if c.Stderr != nil && interfaceEqual(c.Stderr, c.Stdout) {
177 return c.childFiles[1], nil
179 return c.writerDescriptor(c.Stderr)
182 func (c *Cmd) writerDescriptor(w io.Writer) (f *os.File, err error) {
184 f, err = os.OpenFile(os.DevNull, os.O_WRONLY, 0)
185 c.closeAfterStart = append(c.closeAfterStart, f)
189 if f, ok := w.(*os.File); ok {
193 pr, pw, err := os.Pipe()
198 c.closeAfterStart = append(c.closeAfterStart, pw)
199 c.closeAfterWait = append(c.closeAfterWait, pr)
200 c.goroutine = append(c.goroutine, func() error {
201 _, err := io.Copy(w, pr)
207 // Run starts the specified command and waits for it to complete.
209 // The returned error is nil if the command runs, has no problems
210 // copying stdin, stdout, and stderr, and exits with a zero exit
213 // If the command fails to run or doesn't complete successfully, the
214 // error is of type *ExitError. Other error types may be
215 // returned for I/O problems.
216 func (c *Cmd) Run() error {
217 if err := c.Start(); err != nil {
223 // Start starts the specified command but does not wait for it to complete.
224 func (c *Cmd) Start() error {
228 if c.Process != nil {
229 return errors.New("exec: already started")
232 type F func(*Cmd) (*os.File, error)
233 for _, setupFd := range []F{(*Cmd).stdin, (*Cmd).stdout, (*Cmd).stderr} {
234 fd, err := setupFd(c)
238 c.childFiles = append(c.childFiles, fd)
240 c.childFiles = append(c.childFiles, c.ExtraFiles...)
243 c.Process, err = os.StartProcess(c.Path, c.argv(), &os.ProcAttr{
253 for _, fd := range c.closeAfterStart {
257 c.errch = make(chan error, len(c.goroutine))
258 for _, fn := range c.goroutine {
259 go func(fn func() error) {
267 // An ExitError reports an unsuccessful exit by a command.
268 type ExitError struct {
272 func (e *ExitError) Error() string {
273 return e.ProcessState.String()
276 // Wait waits for the command to exit.
277 // It must have been started by Start.
279 // The returned error is nil if the command runs, has no problems
280 // copying stdin, stdout, and stderr, and exits with a zero exit
283 // If the command fails to run or doesn't complete successfully, the
284 // error is of type *ExitError. Other error types may be
285 // returned for I/O problems.
286 func (c *Cmd) Wait() error {
287 if c.Process == nil {
288 return errors.New("exec: not started")
291 return errors.New("exec: Wait was already called")
294 state, err := c.Process.Wait()
295 c.ProcessState = state
298 for _ = range c.goroutine {
299 if err := <-c.errch; err != nil && copyError == nil {
304 for _, fd := range c.closeAfterWait {
310 } else if !state.Success() {
311 return &ExitError{state}
317 // Output runs the command and returns its standard output.
318 func (c *Cmd) Output() ([]byte, error) {
320 return nil, errors.New("exec: Stdout already set")
325 return b.Bytes(), err
328 // CombinedOutput runs the command and returns its combined standard
329 // output and standard error.
330 func (c *Cmd) CombinedOutput() ([]byte, error) {
332 return nil, errors.New("exec: Stdout already set")
335 return nil, errors.New("exec: Stderr already set")
341 return b.Bytes(), err
344 // StdinPipe returns a pipe that will be connected to the command's
345 // standard input when the command starts.
346 func (c *Cmd) StdinPipe() (io.WriteCloser, error) {
348 return nil, errors.New("exec: Stdin already set")
350 if c.Process != nil {
351 return nil, errors.New("exec: StdinPipe after process started")
353 pr, pw, err := os.Pipe()
358 c.closeAfterStart = append(c.closeAfterStart, pr)
359 c.closeAfterWait = append(c.closeAfterWait, pw)
363 // StdoutPipe returns a pipe that will be connected to the command's
364 // standard output when the command starts.
365 // The pipe will be closed automatically after Wait sees the command exit.
366 func (c *Cmd) StdoutPipe() (io.ReadCloser, error) {
368 return nil, errors.New("exec: Stdout already set")
370 if c.Process != nil {
371 return nil, errors.New("exec: StdoutPipe after process started")
373 pr, pw, err := os.Pipe()
378 c.closeAfterStart = append(c.closeAfterStart, pw)
379 c.closeAfterWait = append(c.closeAfterWait, pr)
383 // StderrPipe returns a pipe that will be connected to the command's
384 // standard error when the command starts.
385 // The pipe will be closed automatically after Wait sees the command exit.
386 func (c *Cmd) StderrPipe() (io.ReadCloser, error) {
388 return nil, errors.New("exec: Stderr already set")
390 if c.Process != nil {
391 return nil, errors.New("exec: StderrPipe after process started")
393 pr, pw, err := os.Pipe()
398 c.closeAfterStart = append(c.closeAfterStart, pw)
399 c.closeAfterWait = append(c.closeAfterWait, pr)