Golang可以安全地切换cmd.Stdout

时间:2014-04-09 09:56:40

标签: go exec

我使用Go执行进程并将输出写入文件(日志文件)

    cmd := exec.Command(path)
    cmd.Dir = dir
    t := time.Now()
    t1 := t.Format("20060102-150405")

    fs, err := os.Create(dir + "/var/log/" + t1 + ".std")
    if err == nil {
        cmd.Stdout = fs
    }

我希望每天轮换日志并更改日志文件 http://golang.org/pkg/os/exec/

    // Stdout and Stderr specify the process's standard output and error.
    //
    // If either is nil, Run connects the corresponding file descriptor
    // to the null device (os.DevNull).
    //
    // If Stdout and Stderr are the same writer, at most one
    // goroutine at a time will call Write.
    Stdout io.Writer
    Stderr io.Writer

每天从仲裁goroutine更改cmd.Stdout变量是否安全,或者我必须实现将从Stdout复制到另一个文件并切换文件的goroutine?

1 个答案:

答案 0 :(得分:6)

直接更改这些变量是安全的。但是,如果在实际运行命令后更改它们,则它们将对实际运行的子进程没有影响。旋转正在运行的进程的输出" live"你必须在进程中实现它,或者通过父进程管理所有内容并按照你的建议使用goroutine。

相关问题