Home >Backend Development >Golang >How to Ensure Child Processes Survive Parent Process Termination in systemd?
When executing a program that spawns long-running child processes, it is crucial to ensure that the child processes remain active even after the main process restarts or terminates. Using the command line, this can be achieved by setting the Setsid flag of the exec.Command object to true. This detaches the child process from the parent process's session and process group, allowing it to continue running independently.
However, when launching the main process through systemd, the default KillMode setting in the service configuration file may interfere with the detachment process. By default, systemd's KillMode is set to control-group, which implies that all processes within the unit's control group are terminated when the main process stops.
To resolve this issue and allow the child processes to survive the main process termination, the KillMode setting in the systemd service file needs to be modified.
To change the KillMode setting, edit the systemd service file located at /etc/systemd/system/exectest.service and add the following line within the [Service] section:
KillMode=process
Setting KillMode to process ensures that only the main process itself is killed when the unit is stopped. This ensures that the child processes remain unaffected and continue running independently.
After making the change, save the file and restart the systemd service using the following commands:
sudo systemctl daemon-reload sudo systemctl restart exectest
To verify that the child processes are surviving the parent process termination, use the following steps:
The above is the detailed content of How to Ensure Child Processes Survive Parent Process Termination in systemd?. For more information, please follow other related articles on the PHP Chinese website!