github.com/inazumav/sing-box@v0.0.0-20230926072359-ab51429a14f1/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  		if sUserID > 0 {
    24  			err = outputFile.Chown(sUserID, sGroupID)
    25  			if err != nil {
    26  				outputFile.Close()
    27  				os.Remove(outputFile.Name())
    28  				return err
    29  			}
    30  		}
    31  	}
    32  	err = unix.Dup2(int(outputFile.Fd()), int(os.Stderr.Fd()))
    33  	if err != nil {
    34  		outputFile.Close()
    35  		os.Remove(outputFile.Name())
    36  		return err
    37  	}
    38  	stderrFile = outputFile
    39  	return nil
    40  }