Golang safely switch cmd.Stdout

I execute the process with Go and write the output to a 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 want to rotate the logs and change the log file daily http://golang.org/pkg/os/exec/

  // Stdout and Stderr specify the process 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 the cmd.Stdout variable daily from arbitary goroutine or do I need to implement a goroutine that will copy from Stdout to another file and switch files?

+7
go exec
source share
1 answer

It is safe to directly modify these variables. However, if you change them as soon as the command is run, they will not affect the currently running child process. To turn the output of the working process live, you will have to implement this in the process itself or pass everything through the parent and use goroutine, as you suggest.

+6
source share

All Articles