SEANK.H.LIAO

go fork daemon to background

sometimes you just need a persistent server

fork to background in Go

So, you want to execute a process, forking it to the background and keep it running after the parent process exits.

First.... try not to do this, mysterious persistent daemons is a management nightmare.

But if you need to do it:

 1package main
 2
 3import (
 4        "fmt"
 5        "os/exec"
 6        "syscall"
 7)
 8
 9func main() {
10        cmd := exec.Command("./background-process")
11        cmd.SysProcAttr = &syscall.SysProcAttr{
12                Setsid: true,
13        }
14        cmd.Start()
15        fmt.Println("run, exit")
16}

This makes use of setsid, starting a new process group disassociated with the current tree. In Go, syscall.SysProcAttr.Setsid with a zero Pgid (parent group ID) starts a new group. And os/exec.Cmd.Start doesn't wait for the process to complete.