使用重定向到文件启动分离命令 [英] Start detached command with redirect to file

查看:60
本文介绍了使用重定向到文件启动分离命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在一个分离的进程中启动一个命令,以便它可以在go程序退出后继续执行.我需要将命令的输出重定向到文件.

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

显然,这种重定向不起作用.启动长时间运行的命令后,我立即退出程序,因此无法打开文件并将其绑定到Stdout.

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?

推荐答案

也许您可以尝试使用此方法: https://stackoverflow .com/a/28918814/2728768

Maybe you can try to use this: https://stackoverflow.com/a/28918814/2728768

打开一个文件(并且os.File实现io.Writer),然后将其作为command.Stdout传递就可以了:

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.

这篇关于使用重定向到文件启动分离命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆