Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a program to restart itself? (Linux process)

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;
}
like image 679
bvk256 Avatar asked Nov 28 '11 21:11

bvk256


People also ask

How do I restart a Linux process automatically?

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!

How do I restart a PID process?

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.


Video Answer


1 Answers

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.

like image 189
Richard Wolf Avatar answered Sep 20 '22 09:09

Richard Wolf