Created
          August 28, 2018 14:18 
        
      - 
      
 - 
        
Save viveksyngh/df64846d520d86b64453809e2176dbd5 to your computer and use it in GitHub Desktop.  
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | //CommandTimeoutWithChannel command timeout using channel and goroutine | |
| func CommandTimeoutWithChannel(command string, timeout time.Duration) (string, error) { | |
| cmd := exec.Command("/bin/bash", "-c", command) | |
| var out bytes.Buffer | |
| cmd.Stdout = &out | |
| err := cmd.Start() | |
| if err != nil { | |
| log.Printf("Error : %s", err.Error()) | |
| return err.Error(), err | |
| } | |
| done := make(chan error) | |
| go func() { done <- cmd.Wait() }() | |
| timer := time.After(timeout) | |
| select { | |
| case <-timer: | |
| cmd.Process.Kill() | |
| fmt.Println("Command timed out") | |
| return "Command timed out", errors.New("Command Timeout") | |
| case err := <-done: | |
| if err != nil { | |
| return err.Error(), err | |
| } | |
| return out.String(), nil | |
| } | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment