I'm trying to get my program to restart itself, but nothing seems to work. I tried using fork()
, but after killing the parent
process the child
gets killed too.
CODE
void sigup_handler(int signum) {
int pid = fork();
if (pid == 0) {
execve("prog2", NULL);
}
else
kill(getpid(), SIGTERM);
}
int main() {
puts("Program 2 started.");
signal(SIGHUP, sigup_handler);
sleep(50);
puts("Program 2 terminated.");
return 0;
}
After reloading the systemd manager configuration ( sudo systemctl daemon-reload ), kill your running service and confirm that it is automatically restarted after the time specified by RestartSec has elapsed. Thanks for reading!
You can't restart a process with a pid 1 runs in container, cause the restart operation is just stop and then start , the container would exit immediately when it detect the pid 1 were killed , so the start will never happen. kill -HUP 1 will reload the configuration without kill the process, this equal to restart it.
Why bother with the fork
if you're just going to kill
the parent
? Just do the exec
. The new instance of the program will still be the same process but will effectively be rebooted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With