dor65412 2016-10-25 14:53
浏览 37
已采纳

使用重定向到文件启动分离命令

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 need is something like this:

func main() {
    command := exec.Command("/tmp/test.sh", ">", "/tmp/out")

    if err := command.Start(); err != nil {
        fmt.Fprintln(os.Stderr, "Command failed.", err)
        os.Exit(1)
    }

    fmt.Println("Process ID:", command.Process.Pid)
}

Obviously such redirect doesn't work. As I immediately exit from the program after starting the long running command, I cannot open a file and bind it to the Stdout.

Is there any way to achieve such a redirect?

  • 写回答

2条回答 默认 最新

  • douyi1899 2016-10-25 15:28
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画