Skip to content

Instantly share code, notes, and snippets.

@Paradoxis
Created December 4, 2021 12:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Paradoxis/949906c4117f652e87d339fc41426dce to your computer and use it in GitHub Desktop.
Save Paradoxis/949906c4117f652e87d339fc41426dce to your computer and use it in GitHub Desktop.
GoLang - Daemonize a own process on runtime (MacOS / Linux)
package main
import (
"os"
"time"
"syscall"
)
func main() {
daemonize()
for {
time.Sleep(time.Second)
// do stuff here
}
}
func daemonize() {
var initial = os.Getppid()
syscall.Syscall(syscall.SYS_FORK, 0, 0, 0)
if os.Getppid() == initial {
os.Exit(0)
}
var secondary = os.Getpid()
syscall.Syscall(syscall.SYS_FORK, 0, 0, 0)
if os.Getppid() == secondary {
os.Exit(0)
}
syscall.Syscall(syscall.SYS_SETSID, 0, 0, 0)
syscall.Syscall(syscall.SYS_CLOSE, 0, 0, 0)
syscall.Syscall(syscall.SYS_CLOSE, 1, 0, 0)
syscall.Syscall(syscall.SYS_CLOSE, 2, 0, 0)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment