github.com/sagernet/sing-box@v1.2.7/experimental/libbox/log.go (about)

     1  //go:build darwin || linux
     2  
     3  package libbox
     4  
     5  import (
     6  	"os"
     7  
     8  	"golang.org/x/sys/unix"
     9  )
    10  
    11  var stderrFile *os.File
    12  
    13  func RedirectStderr(path string) error {
    14  	if stats, err := os.Stat(path); err == nil && stats.Size() > 0 {
    15  		_ = os.Rename(path, path+".old")
    16  	}
    17  	outputFile, err := os.Create(path)
    18  	if err != nil {
    19  		return err
    20  	}
    21  	err = unix.Dup2(int(outputFile.Fd()), int(os.Stderr.Fd()))
    22  	if err != nil {
    23  		outputFile.Close()
    24  		os.Remove(outputFile.Name())
    25  		return err
    26  	}
    27  	stderrFile = outputFile
    28  	return nil
    29  }