Created
December 4, 2021 12:30
-
-
Save Paradoxis/949906c4117f652e87d339fc41426dce to your computer and use it in GitHub Desktop.
GoLang - Daemonize a own process on runtime (MacOS / Linux)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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