【发布时间】:2017-01-30 16:42:15
【问题描述】:
我一直在考虑下面的代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
FILE* file;
void signal_handler(int _signal) {
switch(_signal){
case SIGTERM:
fprintf(file, "Ouch, the Daemon Child was killed!\n");
fflush(file);
abort();
default:
fprintf(file, "So what?!\n");
fflush(file);
}
}
int main() {
pid_t pid;
int status;
pid = fork();
if(pid != 0) {
// parent
waitpid(pid, &status, WNOHANG); // daemonize the child
} else {
// child
signal(SIGTERM, signal_handler);
file = fopen("daemon.txt", "w");
while(1) {
sleep(1);
fprintf(file, "Daemon child is alive.\n");
fflush(file);
}
}
return 0;
}
我希望我能在daemon.txt 的末尾找到字符串Ouch, the Daemon Child was killed!,在sudo kill -KILL 之后。然而,这种情况并非如此。我的错在哪里?
【问题讨论】:
-
如果我正确理解了你的代码,“哎呀,守护进程被杀死了!\n”应该在进程收到 SIGTERM 时打印。但是,您向它发送 SIGKILL。你期待什么?
-
在哪里可以找到 kill 信号的完整列表?我提到了tutorialspoint.com/c_standard_library/c_function_signal.htm,但那里没有 SIGKILL
-
信号依赖于操作系统。作为起点,请参阅:pubs.opengroup.org/onlinepubs/009695399/basedefs/signal.h.html,但最好参考操作系统的
signal.h文件。 -
或阅读
signal(3)或signal(7)的手册页,具体取决于操作系统。 -
在 shell 中,
kill -l将列出信号名称/编号。