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

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