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.
我正试图让我的程序重新启动,但似乎没有任何工作。我尝试使用fork(),但在杀死父进程后,孩子也被杀死了。
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;
}
3 个解决方案
#1
13
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.
如果你要杀死父母,为什么还要用叉子呢?做执行官。该程序的新实例仍将是相同的过程,但将有效地重新启动。
#2
3
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.
使用2级分叉。一个父“监视器”应用程序,它会分叉儿童并监控他们的状态。如果孩子死了,监视器会启动一个新的。然后孩子们自己做分叉,做他们必须做的事情。
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.
但是,如果您不需要应用程序的“新”副本与被杀死的副本具有相同的状态,那么使用exec()启动新的独立副本可能是更好的选择,从而节省您必须拥有的坐在那里的监控副本。
#1
13
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.
如果你要杀死父母,为什么还要用叉子呢?做执行官。该程序的新实例仍将是相同的过程,但将有效地重新启动。
#2
3
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.
使用2级分叉。一个父“监视器”应用程序,它会分叉儿童并监控他们的状态。如果孩子死了,监视器会启动一个新的。然后孩子们自己做分叉,做他们必须做的事情。
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.
但是,如果您不需要应用程序的“新”副本与被杀死的副本具有相同的状态,那么使用exec()启动新的独立副本可能是更好的选择,从而节省您必须拥有的坐在那里的监控副本。