Golang可以安全地切换cmd.Stdout

Golang可以安全地切换cmd.Stdout

问题描述:

I execute process with Go and write output to file (log file)

    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
    }

I wish to rotate logs and change log file daily 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

Is it safe to change cmd.Stdout variable daily from arbitary goroutine or I have to implement goroutine that will copy from Stdout to another file and switch files?

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

  cmd:= exec.Command(path)
 cmd.Dir = dir 
t:= time.Now()
 t1:= t.Format(“ 20060102-150405”)
 
 fs,  err:= os.Create(dir +“ / var / log /” + t1 +“ .std”)
如果err == nil {
 cmd.Stdout = fs 
} 
  code>  n  pre> 
 
 

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

  // Stdout和Stderr指定进程的标准输出和错误。
 // 
 //如果两者均为nil, 运行会将相应的文件描述符
 //连接到空设备(os.DevNull)。
 // 
 //如果Stdout和Stderr是同一编写器,则一次最多只能调用一个
 //例程 写入。
 Stdout io.Writer 
 Stderr io.Writer 
  code>  pre> 
 
 

每天从任意goroutine更改cmd.Stdout变量是否安全,否则我必须实现goroutine 日 会从Stdout复制到另一个文件并切换文件吗? p> div>

It is safe to change those variables directly. However, if you change them once the command has actually been run then they will have no effect on the actual running child process. To rotate the output of the running process "live" you will have to implement that in the process itself, or pipe everything through the parent and use a goroutine as you suggest.