我有一个进程,并希望在它被终止时重新启动它。为了实现这一点,我启动了子“守护”进程,该进程使用prctl(PR_SET_PDEATHSIG, SIGHUP);来捕获对其父进程的杀死,并再次启动它。
以下是guardian的代码(日志记录被省略):
void restart (int signal) {
if (getppid() == 1) {
if (fork() == 0) {
execl("./process", 0);
}
exit(1);
}
}
int main() {
prctl(PR_SET_PDEATHSIG, SIGHUP, NULL, NULL, NULL);
struct sigaction new_action, old_action;
new_action.sa_handler = restart;
sigemptyset (&new_action.sa_mask);
new_action.sa_flags = 0;
sigaction (SIGHUP, NULL, &old_action);
if (old_action.sa_handler != SIG_IGN) {
sigaction (SIGHUP, &new_action, NULL);
}
while (getppid() != 1) {
sleep(86400000);
}
return 0;
}和父级:
int main() {
if (fork() == 0) {
execl("./guardian", 0);
}
while (1) {
cout << "I am process\n";
sleep(1);
}
return 0;
}我的问题是它只能工作一次。下面是第一次启动进程时的ps输出:
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
1012 13058 0.0 0.3 20244 1932 pts/1 Ss 08:22 0:00 -sh
1012 22084 0.0 0.1 11484 1004 pts/1 S+ 11:20 0:00 \_ ./process
1012 22085 0.0 0.1 11484 1000 pts/1 S+ 11:20 0:00 \_ [guardian]
1012 12510 0.0 0.3 20784 1712 pts/0 Ss 08:14 0:00 -sh
1012 22088 0.0 0.1 17412 1012 pts/0 R+ 11:20 0:00 \_ ps fu看起来不错。接下来,我用kill -9 22084杀死进程。再一次ps输出:
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
1012 13058 0.0 0.3 20244 1932 pts/1 Ss+ 08:22 0:00 -sh
1012 12510 0.0 0.3 20784 1712 pts/0 Ss 08:14 0:00 -sh
1012 22091 0.0 0.1 17412 1012 pts/0 R+ 11:21 0:00 \_ ps fu
1012 22089 0.0 0.1 11484 996 pts/1 S 11:20 0:00 [process]
1012 22090 0.0 0.1 11484 996 pts/1 S 11:20 0:00 \_ [guardian]当我再次杀死进程时,kill -9 22089 guardian似乎没有得到SIGHUP回调(我检查了日志,这里省略了它们)。
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
1012 13058 0.0 0.3 20244 1932 pts/1 Ss+ 08:22 0:00 -sh
1012 12510 0.0 0.3 20784 1712 pts/0 Rs 08:14 0:00 -sh
1012 22339 0.0 0.1 17412 1008 pts/0 R+ 11:27 0:00 \_ ps fu
1012 22090 0.0 0.1 11484 996 pts/1 S 11:20 0:00 [guardian]我的问题是-为什么卫报没有得到SIGHUP?
我怀疑这可能与后台进程组有关-当进程重新启动时,它在后台组中(比较ps统计中的S+和S)。
发布于 2012-02-10 20:12:39
当您在处理SIGHUP的信号处理程序中时,SIGHUP似乎被阻塞了。fork()和exec()继承了信号掩码,因此你的第二个守护者再也不会收到它了。
在fork()之后的信号处理程序中,在exec()父级之前取消阻止SIGHUP。
https://stackoverflow.com/questions/9227311
复制相似问题