Created
February 5, 2019 09:21
-
-
Save steevehook/c7c1b86694de8873fc48b2ebd1703ec8 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
| package main | |
| import ( | |
| "fmt" | |
| "log" | |
| "os" | |
| "os/exec" | |
| ) | |
| type Data struct { | |
| output []byte | |
| error error | |
| } | |
| func runCommand(ch chan<- Data) { | |
| cmd := exec.Command("ls", "-la") | |
| data, err := cmd.CombinedOutput() | |
| ch <- Data{ | |
| error: err, | |
| output: data, | |
| } | |
| } | |
| func main() { | |
| c := make(chan Data) | |
| // This will work in background | |
| go runCommand(c) | |
| // Do other things here | |
| // When everything is done, you can check your background process result | |
| res := <-c | |
| if res.error != nil { | |
| fmt.Println("Failed to execute command: ", res.error) | |
| } else { | |
| // You will be here, runCommand has finish successfuly | |
| f, err := os.Create("output.txt") | |
| if err != nil { | |
| log.Fatal(err) | |
| } | |
| _, err = f.Write(res.output) | |
| if err != nil { | |
| log.Fatal(err) | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment