我一直在考虑以下代码
#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< 之后
.然而,这种情况并非如此。我的错在哪里?
最佳答案
您似乎正在捕获 SIGTERM
,然后发送 SIGKILL
,但您没有处理程序。如果您使用 kill -TERM $pid
而不是 kill -KILL
,您可能会看到预期的输出。
关于c - 后台进程和文件输出的信号处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41946995/