“syscall”
“os”
“log”
)
func daemon (nochdir, noclose int) int {
var ret uintptr
var err uintptr
// already a daemon
if syscall.Getppid() == 1 { return 0 }
// fork off the parent process
ret, _, err = syscall.RawSyscall(syscall.SYS_FORK, 0, 0, 0)
if err != 0 { return -1 }
// failure
if ret < 0 { os.Exit(-1) }
// 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 != 0 {
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(fd, os.Stdin.Fd())
syscall.Dup2(fd, os.Stdout.Fd())
syscall.Dup2(fd, os.Stderr.Fd())
}
}
return 0
}
// usage example: daemon(0, 0)
参考:http://code.google.com/p/go/issues/detail?id=227
© 谭俊青 发布在 MySQL性能、MySQL Cluster集群、MySQL HA高可用等研究 – MySQL实验室, 2011.
可以任意转载, 但转载时务必以超链接形式标明文章原始出处 和 作者信息。
链接: http://www.mysqlab.net/blog/2011/12/daemon-function-for-go-language/
转载请注明:爱开源 » daemon function for Go language