2023-04-09 22:32:15 +08:00
|
|
|
//go:build darwin || linux
|
|
|
|
|
|
|
|
package libbox
|
|
|
|
|
|
|
|
import (
|
|
|
|
"os"
|
|
|
|
|
|
|
|
"golang.org/x/sys/unix"
|
|
|
|
)
|
|
|
|
|
|
|
|
var stderrFile *os.File
|
|
|
|
|
|
|
|
func RedirectStderr(path string) error {
|
|
|
|
if stats, err := os.Stat(path); err == nil && stats.Size() > 0 {
|
|
|
|
_ = os.Rename(path, path+".old")
|
|
|
|
}
|
|
|
|
outputFile, err := os.Create(path)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
err = unix.Dup2(int(outputFile.Fd()), int(os.Stderr.Fd()))
|
|
|
|
if err != nil {
|
|
|
|
outputFile.Close()
|
|
|
|
os.Remove(outputFile.Name())
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
stderrFile = outputFile
|
|
|
|
return nil
|
|
|
|
}
|
2023-04-21 17:29:00 +08:00
|
|
|
|
|
|
|
func RedirectStderrAsUser(path string, uid, gid int) error {
|
|
|
|
if stats, err := os.Stat(path); err == nil && stats.Size() > 0 {
|
|
|
|
_ = os.Rename(path, path+".old")
|
|
|
|
}
|
|
|
|
outputFile, err := os.Create(path)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
err = outputFile.Chown(uid, gid)
|
|
|
|
if err != nil {
|
|
|
|
outputFile.Close()
|
|
|
|
os.Remove(outputFile.Name())
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
err = unix.Dup2(int(outputFile.Fd()), int(os.Stderr.Fd()))
|
|
|
|
if err != nil {
|
|
|
|
outputFile.Close()
|
|
|
|
os.Remove(outputFile.Name())
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
stderrFile = outputFile
|
|
|
|
return nil
|
|
|
|
}
|