Home > Backend Development > Golang > How can I prevent systemd from killing child processes when the parent process terminates?

How can I prevent systemd from killing child processes when the parent process terminates?

Barbara Streisand
Release: 2024-12-21 04:57:09
Original
761 people have browsed it

How can I prevent systemd from killing child processes when the parent process terminates?

Handling Child Processes in Systemd: Resolving Process Detachment Issues

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())
    }
}
Copy after login

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
Copy after login

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
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template