本文整理匯總了Golang中syscall.Dup2函數的典型用法代碼示例。如果您正苦於以下問題:Golang Dup2函數的具體用法?Golang Dup2怎麽用?Golang Dup2使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了Dup2函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: daemon
func daemon(nochdir, noclose int) int {
var ret uintptr
var err syscall.Errno
ret, _, err = syscall.Syscall(syscall.SYS_FORK, 0, 0, 0)
if err != 0 {
return -1
}
switch ret {
case 0:
break
default:
os.Exit(0)
}
pid, _ := syscall.Setsid()
if pid == -1 {
return -1
}
if nochdir == 0 {
os.Chdir("/")
}
if noclose == 0 {
f, e := os.Open("/dev/null")
if e == nil {
fd := int(f.Fd())
syscall.Dup2(fd, int(os.Stdin.Fd()))
syscall.Dup2(fd, int(os.Stdout.Fd()))
syscall.Dup2(fd, int(os.Stderr.Fd()))
}
}
return 0
}
示例2: CaptureStream
func CaptureStream(file *os.File) (*os.File, func(), error) {
pipeR, pipeW, err := os.Pipe()
if err != nil {
return nil, nil, err
}
bkupFD, err := syscall.Dup(int(file.Fd()))
if err != nil {
pipeW.Close()
pipeR.Close()
return nil, nil, err
}
err = syscall.Dup2(int(pipeW.Fd()), int(file.Fd()))
if err != nil {
syscall.Close(bkupFD)
pipeW.Close()
pipeR.Close()
}
cleanFunc := func() {
syscall.Dup2(bkupFD, int(file.Fd()))
syscall.Close(bkupFD)
pipeW.Close()
pipeR.Close()
}
return pipeR, cleanFunc, nil
}
示例3: SetDaemonMode
func (this torUtil) SetDaemonMode(nochdir, noclose int) int {
if syscall.Getppid() == 1 {
return 0
}
ret, ret2, err := syscall.RawSyscall(syscall.SYS_FORK, 0, 0, 0)
if err != 0 {
return -1
}
if ret2 < 0 {
os.Exit(-1)
}
if ret > 0 {
os.Exit(0)
}
syscall.Umask(0)
s_ret, s_errno := syscall.Setsid()
if s_ret < 0 {
return -1
}
if nochdir == 0 {
os.Chdir("/")
}
if noclose == 0 {
f, e := os.OpenFile("/dev/null", os.O_RDWR, 0)
if e == nil {
fd := f.Fd()
syscall.Dup2(int(fd), int(os.Stdin.Fd()))
syscall.Dup2(int(fd), int(os.Stdout.Fd()))
syscall.Dup2(int(fd), int(os.Stderr.Fd()))
}
}
return 0
}
示例4: daemon
func daemon(nochdir, noclose int) int {
var ret, ret2 uintptr
var err syscall.Errno
darwin := runtime.GOOS == "darwin"
// already a daemon
if syscall.Getppid() == 1 {
return 0
}
// fork off the parent process
ret, ret2, err = syscall.RawSyscall(syscall.SYS_FORK, 0, 0, 0)
if err != 0 {
return -1
}
// failure
if ret2 < 0 {
os.Exit(-1)
}
// handle exception for darwin
if darwin && ret2 == 1 {
ret = 0
}
// if we got a good PID, then we call exit the parent process.
if ret > 0 {
os.Exit(0)
}
/* Change the file mode mask */
_ = syscall.Umask(0)
// create a new SID for the child process
s_ret, s_errno := syscall.Setsid()
if s_errno != nil {
log.Printf("Error: syscall.Setsid errno: %d", s_errno)
}
if s_ret < 0 {
return -1
}
if nochdir == 0 {
os.Chdir("/")
}
if noclose == 0 {
f, e := os.OpenFile("/dev/null", os.O_RDWR, 0)
if e == nil {
fd := f.Fd()
syscall.Dup2(int(fd), int(os.Stdin.Fd()))
syscall.Dup2(int(fd), int(os.Stdout.Fd()))
syscall.Dup2(int(fd), int(os.Stderr.Fd()))
}
}
return 0
}
示例5: StartInterceptingOutput
func (interceptor *outputInterceptor) StartInterceptingOutput() error {
if interceptor.intercepting {
return errors.New("Already intercepting output!")
}
interceptor.intercepting = true
var err error
interceptor.redirectFile, err = ioutil.TempFile("", "ginkgo")
if err != nil {
return err
}
interceptor.stdoutPlaceholder, err = ioutil.TempFile("", "ginkgo")
if err != nil {
return err
}
interceptor.stderrPlaceholder, err = ioutil.TempFile("", "ginkgo")
if err != nil {
return err
}
syscall.Dup2(1, int(interceptor.stdoutPlaceholder.Fd()))
syscall.Dup2(2, int(interceptor.stderrPlaceholder.Fd()))
syscall.Dup2(int(interceptor.redirectFile.Fd()), 1)
syscall.Dup2(int(interceptor.redirectFile.Fd()), 2)
return nil
}
示例6: initLogging
func initLogging(logLevelStr string, logPath string) {
logLevel, err := logging.LogLevel(logLevelStr)
if err != nil {
log.Fatal("Invalid log level specified")
}
var formatStdout = logging.MustStringFormatter(
"%{color}%{time:15:04:05.000} %{shortfunc} ▶ %{level:.4s} %{color:reset} %{message}",
)
stdout := logging.NewLogBackend(os.Stdout, "", 0)
formatter := logging.NewBackendFormatter(stdout, formatStdout)
stdoutLeveled := logging.AddModuleLevel(formatter)
stdoutLeveled.SetLevel(logLevel, "")
syslogBackend, err := logging.NewSyslogBackendPriority("cluegetter", syslog.LOG_MAIL)
if err != nil {
Log.Fatal(err)
}
if logPath != "" {
logFile, err := os.OpenFile(logPath, os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
Log.Fatal(err)
}
syscall.Dup2(int(logFile.Fd()), 1)
syscall.Dup2(int(logFile.Fd()), 2)
}
logging.SetBackend(syslogBackend, stdoutLeveled)
}
示例7: InitLogging
// Initializes logrus. Returns a pointer to `os.File` that should be `Close`d
// via `defer` in the main func.
func InitLogging(debug bool, logFile string) *os.File {
var logFp *os.File
if debug {
log.SetLevel(log.DebugLevel)
}
if logFile != "" {
logFp, err := os.OpenFile(logFile, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0600)
CheckError(fmt.Sprintf("error opening %s", logFile), err)
// ensure panic output goes to log file
syscall.Dup2(int(logFp.Fd()), 1)
syscall.Dup2(int(logFp.Fd()), 2)
// log as JSON
log.SetFormatter(&log.JSONFormatter{})
// send output to file
log.SetOutput(logFp)
}
workers.Logger = log.WithField("name", "worker")
return logFp
}
示例8: Daemonize
func Daemonize() (e error) {
// var ret, err uintptr
ret, _, err := syscall.Syscall(syscall.SYS_FORK, 0, 0, 0)
if err != 0 {
return fmt.Errorf("fork error: %d", err)
}
if ret != 0 {
// Parent
os.Exit(0)
}
// We are now child
if err, _ := syscall.Setsid(); err < 0 {
return fmt.Errorf("setsid error: %d", err)
}
os.Chdir("/")
f, e := os.OpenFile(os.DevNull, os.O_RDWR, 0)
if e != nil {
return
}
fd := int(f.Fd())
syscall.Dup2(fd, int(os.Stdin.Fd()))
syscall.Dup2(fd, int(os.Stdout.Fd()))
syscall.Dup2(fd, int(os.Stderr.Fd()))
return nil
}
示例9: main
func main() {
// Prepare the HTTP server
server := &http.Server{
Addr: "127.0.0.1:8081",
}
metricsPort := "8082"
flag.StringVar(&metricsPort, "mport", metricsPort, "metrics service port")
flag.StringVar(&server.Addr, "addr", server.Addr, "http service address (TCP address or absolute path for UNIX socket)")
origin := flag.String("origin", "", "websocket server checks Origin headers against this scheme://host[:port]")
logpath := flag.String("log", "", "Log file (absolute path)")
flag.Parse()
if strings.HasPrefix(*logpath, "/") {
logf, err := os.OpenFile(*logpath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Fatalf("error opening log file: %v", err)
}
defer func() {
log.Printf("********** pid %d stopping **********", os.Getpid())
logf.Close()
}()
if err = syscall.Dup2(int(logf.Fd()), syscall.Stdout); err != nil {
log.Fatalf("error redirecting stdout to file: %v", err)
}
if err = syscall.Dup2(int(logf.Fd()), syscall.Stderr); err != nil {
log.Fatalf("error redirecting stderr to file: %v", err)
}
log.SetFlags(log.Ldate | log.Lmicroseconds | log.LUTC)
log.Printf("********** pid %d starting **********", os.Getpid())
}
// Initialize metrics registry with expected stats
go startMetrics(metricsPort)
incr("websockets", 0) // number of connected websockets
incr("channels", 0) // number of subscribed channels
mark("postmsgs", 0) // rate of POST messages
mark("websocketmsgs", 0) // rate of WS messages
mark("drops", 0) // rate of messages sent to nobody
mark("sends", 0) // rate of messages sent to somebody
// Start the server
server.Handler = newHandler(*origin)
http.Handle("/", server.Handler)
if strings.HasPrefix(server.Addr, "/") {
ln, err := net.Listen("unix", server.Addr)
if err != nil {
panic(err)
}
closeListenerOnSignals(ln)
server.Serve(ln)
} else {
server.ListenAndServe()
}
}
示例10: _not_work_Fork
func _not_work_Fork(closeno bool) (pid int, err error) {
// don't run this
// not work with go threads
// see: http://code.google.com/p/go/issues/detail?id=227
darwin := runtime.GOOS == "darwin"
// already a daemon
if syscall.Getppid() == 1 {
return 0, nil
}
// fork off the parent process
ret, ret2, errno := syscall.RawSyscall(syscall.SYS_FORK, 0, 0, 0)
if errno != 0 {
return -1, fmt.Errorf("Fork failure: %s", errno)
}
// failure
if ret2 < 0 {
return -1, fmt.Errorf("Fork failure")
}
// handle exception for darwin
if darwin && ret2 == 1 {
ret = 0
}
// if we got a good PID, then we call exit the parent process.
if ret > 0 {
return 0, nil
}
// create a new SID for the child process
s_ret, s_errno := syscall.Setsid()
if s_errno != nil {
return -1, fmt.Errorf("Error: syscall.Setsid: %s", s_errno)
}
if s_ret < 0 {
return -1, fmt.Errorf("Error: syscall.Setsid: %s", s_errno)
}
if closeno {
f, e := os.OpenFile("/dev/null", os.O_RDWR, 0)
if e == nil {
fd := int(f.Fd())
syscall.Dup2(fd, int(os.Stdin.Fd()))
syscall.Dup2(fd, int(os.Stdout.Fd()))
syscall.Dup2(fd, int(os.Stderr.Fd()))
}
}
return os.Getpid(), nil
}
示例11: setupLogging
func (this *Start) setupLogging(logFile, logLevel, crashLogFile string) {
level := log.DEBUG
switch logLevel {
case "info":
level = log.INFO
case "warn":
level = log.WARNING
case "error":
level = log.ERROR
case "debug":
level = log.DEBUG
case "trace":
level = log.TRACE
case "alarm":
level = log.ALARM
}
for _, filter := range log.Global {
filter.Level = level
}
log.LogBufferLength = 32 // default 32, chan cap
if logFile == "stdout" {
log.AddFilter("stdout", level, log.NewConsoleLogWriter())
} else {
log.DeleteFilter("stdout")
filer := log.NewFileLogWriter(logFile, true, true, 0)
filer.SetFormat("[%d %T] [%L] (%S) %M")
filer.SetRotateSize(0)
filer.SetRotateLines(0)
filer.SetRotateDaily(true)
log.AddFilter("file", level, filer)
}
if crashLogFile != "" {
f, err := os.OpenFile(crashLogFile, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
panic(err)
}
syscall.Dup2(int(f.Fd()), int(os.Stdout.Fd()))
syscall.Dup2(int(f.Fd()), int(os.Stderr.Fd()))
fmt.Fprintf(os.Stderr, "\n%s %s (build: %s)\n===================\n",
time.Now().String(),
gafka.Version, gafka.BuildId)
}
}
示例12: main
func main() {
var opts Options
_, err := flags.Parse(&opts)
if err != nil {
os.Exit(1)
}
if opts.Debug {
log.SetLevel(log.DebugLevel)
}
if opts.LogFile != "" {
logFp, err := os.OpenFile(opts.LogFile, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0600)
checkError(fmt.Sprintf("error opening %s", opts.LogFile), err)
defer logFp.Close()
// ensure panic output goes to log file
syscall.Dup2(int(logFp.Fd()), 1)
syscall.Dup2(int(logFp.Fd()), 2)
// log as JSON
log.SetFormatter(&log.JSONFormatter{})
// send output to file
log.SetOutput(logFp)
}
log.Debug("hi there! (tickertape tickertape)")
log.Infof("version: %s", version)
vaultClient, err := helpers.NewVaultClient(opts.VaultAddr, opts.VaultToken)
checkError("creating Vault client", err)
consulClient, err := consulapi.NewClient(consulapi.DefaultConfig())
checkError("creating Consul client", err)
router := mux.NewRouter()
registrar := instance.NewRegistrar(vaultClient)
v1 := v1.NewCentralBooking(
registrar,
consulClient.Catalog(),
vaultClient.GetEndpoint(),
)
v1.InstallHandlers(router.PathPrefix("/v1").Subrouter())
httpServer := &http.Server{
Addr: fmt.Sprintf(":%d", opts.HttpPort),
Handler: Log(router),
}
checkError("launching HTTP server", httpServer.ListenAndServe())
}
示例13: CaptureOutputToFd
// CaptureOutputToFd redirects the current process' stdout and stderr file
// descriptors to the given file descriptor, using the dup2 syscall.
func CaptureOutputToFd(fd int) error {
err := syscall.Dup2(fd, syscall.Stdout)
if err != nil {
return err
}
err = syscall.Dup2(fd, syscall.Stderr)
if err != nil {
return err
}
return nil
}
示例14: Test_println
func Test_println(t *testing.T) {
cleanup1 := testutils.Chtemp()
defer cleanup1()
rfile, err := os.Create("stdout")
if err != nil {
panic(err)
}
// save a copy of stdout in another fd
stdout_fd := int(os.Stdout.Fd())
save_stdout, err := syscall.Dup(stdout_fd)
if err != nil {
panic(err)
}
// redirect stdout to rfile
err = syscall.Dup2(int(rfile.Fd()), stdout_fd)
if err != nil {
panic(err)
}
cleanup2 := func() {
rfile.Close()
err = syscall.Dup2(save_stdout, stdout_fd)
if err != nil {
panic(err)
}
syscall.Close(save_stdout)
}
defer cleanup2()
args := RuntimeArgs{
BasicArgs: types.MakeBasicArgs(nil, []types.FuObject{}, nil),
}
result, errs := fn_println(args)
assert.Nil(t, result)
assert.Equal(t, 0, len(errs))
data, err := ioutil.ReadFile("stdout")
assert.Nil(t, err)
assert.Equal(t, "\n", string(data))
rfile.Truncate(0)
rfile.Seek(0, 0)
args.SetArgs(types.MakeStringList("hello", "world").List())
fn_println(args)
data, err = ioutil.ReadFile("stdout")
assert.Nil(t, err)
assert.Equal(t, "hello world\n", string(data))
rfile.Truncate(0)
rfile.Seek(0, 0)
}
示例15: Detach
// detach detaches from the origin stdin/out/err and makes
// sure the CWD is no longer inside the original host rootfs
func Detach(redirectStdout, redirectStderr string) {
os.Chdir("/")
devNull := must(os.Open("/dev/null"))
syscall.Dup2(int(devNull.Fd()), int(os.Stdin.Fd()))
newStdout := must(os.OpenFile(redirectStdout, os.O_WRONLY|os.O_CREATE, 0700))
syscall.Dup2(int(newStdout.Fd()), int(os.Stdout.Fd()))
newStderr := must(os.OpenFile(redirectStderr, os.O_WRONLY|os.O_CREATE, 0700))
syscall.Dup2(int(newStderr.Fd()), int(os.Stderr.Fd()))
}