• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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, args ...string) ([]byte, error) {
27	b := bytes.Buffer{}
28	c := exec.Command(exe, args...)
29	c.Dir = wd
30	c.Env = env
31	c.Stdout = &b
32	c.Stderr = &b
33
34	if err := c.Start(); err != nil {
35		return nil, err
36	}
37
38	res := make(chan error)
39	go func() { res <- c.Wait() }()
40
41	select {
42	case <-time.NewTimer(timeout).C:
43		c.Process.Kill()
44		return b.Bytes(), ErrTimeout{exe, timeout}
45	case err := <-res:
46		return b.Bytes(), err
47	}
48}
49