Quantcast
Channel: CodeSection,代码区,Linux操作系统:Ubuntu_Centos_Debian - CodeSec
Viewing all articles
Browse latest Browse all 11063

Linux下守护进程的Golang语言实现

$
0
0

=Start=

缘由:

以后可能要用Golang语言写一个daemon程序(守护进程)运行在服务器上,以进行一些信息收集的工作。之前只是简单知道什么是守护进程,但对于一些细节以及该如何用Golang进行编写都不太清楚,所以需要先学习、准备一下。

正文: 参考解答:

……待补充……

package main import ( "fmt" "log" "os" "os/signal" "runtime" "syscall" "time" ) funcdaemon(nochdir, nocloseint) int { var ret, ret2uintptr var errsyscall.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 } funcmain() { daemon(0, 1) for { fmt.Println("hello") time.Sleep(1 * time.Second) } }

……待补充……

参考链接: Go到目前还没有解决成为守护进程(Daemonize)的问题吧?各位是怎么解决的?
https://segmentfault.com/q/1010000000699471 Golang创建daemon程序
http://shanks.leanote.com/post/Go%E5%88%9B%E5%BB%BAdaemon%E7%A8%8B%E5%BA%8F Go语言daemon启动的解决方法.linux平台
http://blog.csdn.net/fyxichen/article/details/50541449 How to create a daemon process in Golang?
http://stackoverflow.com/questions/23736046/how-to-create-a-daemon-process-in-golang https://github.com/sevlyar/go-daemon
https://github.com/takama/daemon
https://github.com/VividCortex/godaemon
https://github.com/fiorix/go-daemon How do I get my Golang web server to run in the background?
http://stackoverflow.com/questions/12486691/how-do-i-get-my-golang-web-server-to-run-in-the-background supervisor运行golang守护进程
http://www.01happy.com/supervisor-golang-daemon/ 用golang启动一个daemon
http://www.cnblogs.com/toby/p/3262516.html

=END=


Viewing all articles
Browse latest Browse all 11063

Trending Articles