简体   繁体   中英

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;
}

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.

Use 2 levels of forking. A parent "monitor" app which forks off children and monitors their status. If a child dies, the monitor starts up a new one. The children then do their own forking to do whatever it is they have to do.

However, if you don't need the 'new' copy of the app to have the same state as the one that's being killed, then using exec() to start a fresh independent copy is likely a better option, saving you having to have that monitor copy sitting around.

您可以使用守护进程(3),然后使用execve(2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM