-
-
Save SufyanDahalan/89f277b58b408c4c2acb8cba8b1ce06d to your computer and use it in GitHub Desktop.
Using os.StartProcess() in Go for platform-independent system command execution.
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 ( | |
| "os" | |
| "os/exec" | |
| ) | |
| func Start(args ...string) (p *os.Process, err error) { | |
| if args[0], err = exec.LookPath(args[0]); err == nil { | |
| var procAttr os.ProcAttr | |
| procAttr.Files = []*os.File{os.Stdin, | |
| os.Stdout, os.Stderr} | |
| p, err := os.StartProcess(args[0], args, &procAttr) | |
| if err == nil { | |
| return p, nil | |
| } | |
| } | |
| return nil, err | |
| } | |
| func main() { | |
| if proc, err := Start("ping", "-c 3", "www.google.com"); err == nil { | |
| proc.Wait() | |
| } | |
| if proc, err := Start("zsh"); err == nil { | |
| proc.Wait() | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment