Start detached command with redirect to file

前端 未结 2 1122
心在旅途
心在旅途 2021-01-15 05:59

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

2条回答
  •  长发绾君心
    2021-01-15 06:15

    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.

提交回复
热议问题