github.com/coreos/mantle@v0.13.0/system/exec/exec.go (about) 1 // Copyright 2015 CoreOS, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 // exec is extension of the standard os.exec package. 16 // Adds a handy dandy interface and assorted other features. 17 package exec 18 19 import ( 20 "context" 21 "io" 22 "os/exec" 23 "syscall" 24 ) 25 26 var ( 27 // for equivalence with os/exec 28 ErrNotFound = exec.ErrNotFound 29 LookPath = exec.LookPath 30 ) 31 32 // An exec.Cmd compatible interface. 33 type Cmd interface { 34 // Methods provided by exec.Cmd 35 CombinedOutput() ([]byte, error) 36 Output() ([]byte, error) 37 Run() error 38 Start() error 39 StderrPipe() (io.ReadCloser, error) 40 StdinPipe() (io.WriteCloser, error) 41 StdoutPipe() (io.ReadCloser, error) 42 Wait() error 43 44 // Simplified wrapper for Process.Kill + Wait 45 Kill() error 46 47 // Simplified wrapper for Process.Pid 48 Pid() int 49 } 50 51 // Basic Cmd implementation based on exec.Cmd 52 type ExecCmd struct { 53 *exec.Cmd 54 cancel context.CancelFunc 55 } 56 57 func Command(name string, arg ...string) *ExecCmd { 58 return CommandContext(context.Background(), name, arg...) 59 } 60 61 func CommandContext(ctx context.Context, name string, arg ...string) *ExecCmd { 62 ctx, cancel := context.WithCancel(ctx) 63 return &ExecCmd{ 64 Cmd: exec.CommandContext(ctx, name, arg...), 65 cancel: cancel, 66 } 67 } 68 69 func (cmd *ExecCmd) Kill() error { 70 cmd.cancel() 71 err := cmd.Wait() 72 if err == nil { 73 return nil 74 } 75 76 if eerr, ok := err.(*exec.ExitError); ok { 77 status := eerr.Sys().(syscall.WaitStatus) 78 if status.Signal() == syscall.SIGKILL { 79 return nil 80 } 81 } 82 83 return err 84 } 85 86 func (cmd *ExecCmd) Pid() int { 87 return cmd.Process.Pid 88 } 89 90 // IsCmdNotFound reports true if the underlying error was exec.ErrNotFound. 91 func IsCmdNotFound(err error) bool { 92 if eerr, ok := err.(*exec.Error); ok && eerr.Err == ErrNotFound { 93 return true 94 } 95 return false 96 }