1// Copyright 2019 The SwiftShader Authors. All Rights Reserved. 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 15package shell 16 17import ( 18 "bytes" 19 "os/exec" 20 "time" 21) 22 23// Exec runs the executable exe with the given arguments, in the working 24// directory wd, with the custom environment flags. 25// If the process does not finish within timeout a errTimeout will be returned. 26func Exec(timeout time.Duration, exe, wd string, env []string, toStdin string, args ...string) ([]byte, error) { 27 stdin := &bytes.Buffer{} 28 stdin.WriteString(toStdin) 29 30 b := bytes.Buffer{} 31 c := exec.Command(exe, args...) 32 c.Dir = wd 33 c.Env = env 34 c.Stdin = stdin 35 c.Stdout = &b 36 c.Stderr = &b 37 38 if err := c.Start(); err != nil { 39 return nil, err 40 } 41 42 res := make(chan error) 43 go func() { res <- c.Wait() }() 44 45 select { 46 case <-time.NewTimer(timeout).C: 47 c.Process.Kill() 48 return b.Bytes(), ErrTimeout{exe, timeout} 49 case err := <-res: 50 return b.Bytes(), err 51 } 52} 53