Golang Service Program Daemon Pit record

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.