Golang切换cmd.Stdout是否安全?

6
我使用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变量是安全的吗?还是我需要实现一个goroutine,将其从Stdout复制到另一个文件并切换文件?

1个回答

6

直接更改这些变量是安全的。但是,如果您在命令已经运行后再更改它们,则它们对于实际运行的子进程将没有影响。要“实时”旋转运行进程的输出,您需要在进程本身中实现该功能,或通过父进程管道传递所有内容,并像您建议的那样使用goroutine。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接