This is a created article in which the information may have evolved or changed.
Before writing the habit of c/cpp, all know that you can use the Daemon function on Linux to facilitate the implementation of the daemon. Recently switched to go, want to do the same, the first thought is based on CGO direct call, similar to the following code:
//#include<unistd.h>import "C"func Daemon() { C.daemon(1,0)}
The above code can actually execute successfully, but the problem comes along. Test, I found that the use of the code snippet of the program, the test will randomly appear the program infinite suspended animation situation, most of Google's results are said to be Golang Scheduler and Linux fork system call incompatibility caused, you have to know the details, but also hope to enlighten!
No way, then based on the stack overflow enthusiastic netizen's solution, using similar methods to achieve daemon, note the use of related command line parameters to control the call:
func Daemon(){ cmd := exec.Command(os.Args[0]) cmd.Stdin = nil cmd.Stdout = nil cmd.Stderr = nil cmd.SysProcAttr = &syscall.SysProcAttr{Setsid:true} err := cmd.Start() if err == nil { cmd.Process.Release() os.Exit(0) }}
It is amazing that using this method to implement the daemon, the test did not appear in the case of random animation of the program.