github.com/searKing/golang/go@v1.2.74/os/exec/timeout.go (about)

     1  // Copyright 2020 The searKing Author. 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.
     4  
     5  package exec
     6  
     7  import (
     8  	"context"
     9  	"io"
    10  	"os/exec"
    11  	"time"
    12  )
    13  
    14  func CommandWithTimeoutHandler(timeout time.Duration, name string, arg ...string) (data []byte, err error) {
    15  	ctx, stop := context.WithTimeout(context.Background(), timeout)
    16  	go func() {
    17  		data, err = exec.Command(name, arg...).CombinedOutput()
    18  		stop()
    19  	}()
    20  	select {
    21  	case <-ctx.Done():
    22  		if ctx.Err() == context.Canceled {
    23  			return data, nil
    24  		}
    25  		return nil, ctx.Err()
    26  	}
    27  }
    28  
    29  func CommandWithTimeout(handle func(io.Reader), timeout time.Duration, name string, arg ...string) (err error) {
    30  	cs, err := newCommandServerWithTimeout(handle, timeout, name, arg...)
    31  	if err != nil {
    32  		return err
    33  	}
    34  	err = cs.wait()
    35  	if err != nil {
    36  		cs.Stop()
    37  		return err
    38  	}
    39  	return nil
    40  }
    41  func newCommandServerWithTimeout(handle func(io.Reader), timeout time.Duration, name string, args ...string) (*commandServer, error) {
    42  	ctx, stop := context.WithTimeout(context.Background(), timeout)
    43  	return newCommandServer(ctx, stop, handle, name, args...)
    44  }