I\'m trying to start a command in a detached process so that it can continue after go program exits. I need to redirect the output of the command to a file.
What I n
Maybe you can try to use this: https://stackoverflow.com/a/28918814/2728768
Opening a file (and os.File
implements io.Writer
), and then passing it as the command.Stdout
could do the trick:
func main() {
command := exec.Command("./tmp/test.sh")
f, err := os.OpenFile("/tmp/out", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
fmt.Printf("error opening file: %v", err)
}
defer f.Close()
// On this line you're going to redirect the output to a file
command.Stdout = f
if err := command.Start(); err != nil {
fmt.Fprintln(os.Stderr, "Command failed.", err)
os.Exit(1)
}
fmt.Println("Process ID:", command.Process.Pid)
}
Not sure this could be a viable solution for your case. I've tried it locally and it seems working... remember that your user should be able to create/update the file.