Home >Backend Development >Golang >How can I prevent systemd from killing child processes when the parent process terminates?
When spawning long-running child processes, it's crucial to ensure their survival beyond the lifespan of the main process, especially when managed by systemd. In some scenarios, child processes may terminate unexpectedly, leaving critical background tasks unhandled.
Consider the following issue encountered while attempting to create a main process that starts child processes using the go programming language:
package main import ( "log" "os" "os/exec" "syscall" "time" ) func main() { if len(os.Args) == 2 && os.Args[1] == "child" { for { time.Sleep(time.Second) } } else { cmd := exec.Command(os.Args[0], "child") cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true} log.Printf("child exited: %v", cmd.Run()) } }
When executing this program from the terminal, the child process persists even after the main process is stopped or terminated (Ctrl Z and kill -INT 7914). However, when the main process is started as a systemd service, the child process also terminates abruptly.
To resolve this issue, modify the systemd service file (/etc/systemd/system/exectest.service) by adding the following line:
KillMode=process
This setting instructs systemd to kill only the main process, allowing the child processes to continue running. By default, systemd uses control-group mode, which kills all processes within the same control group as the main process.
The updated systemd service file:
[Unit] Description=ExecTest [Service] Type=simple ExecStart=/home/snowm/src/exectest/exectest User=snowm KillMode=process [Install] WantedBy=multi-user.target
With this modification, the child processes will survive the termination of the main process, ensuring the stability and continuity of background tasks.
The above is the detailed content of How can I prevent systemd from killing child processes when the parent process terminates?. For more information, please follow other related articles on the PHP Chinese website!