Created
September 12, 2012 07:09
-
-
Save yanunon/3704856 to your computer and use it in GitHub Desktop.
go daemon
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Change from http://www.mysqlab.net/blog/2011/12/daemon-function-for-go-language/ | |
//For go 1.0.2 | |
package daemon | |
import ( | |
"syscall" | |
"os" | |
"log" | |
) | |
func Daemon(nochdir, noclose int) int { | |
var ret, ret2 uintptr | |
var err syscall.Errno | |
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_errno != nil { | |
log.Printf("Error: syscall.Setsid error: %s", 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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment