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条)

报告相同问题?

悬赏问题

  • ¥35 引用csv数据文件(4列1800行),通过高斯-赛德尔法拟合曲线,在选取(每五十点取1点)数据,求该数据点的曲率中心。
  • ¥20 程序只发送0X01,串口助手显示不正确,配置看了没有问题115200-8-1-no,如何解决?
  • ¥15 Google speech command 数据集获取
  • ¥15 vue3+element-plus页面崩溃
  • ¥15 像这种代码要怎么跑起来?
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧