c - 后台进程和文件输出的信号处理

标签 c unix signals fork

我一直在考虑以下代码

#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/

相关文章:

c - fscanf 有 2 个文件和多行

php - 从 Perl 在后台运行作业,无需等待返回

linux - 光盘 && ls | grep : How to execute a command in the current shell and pass the output

c++ - 按钮点击的低延迟捕获

代码效果很好,但我不知道如何在第二步中进行逆向处理

c - 结构与另一个结构

c - malloc 链表时出现段错误

javascript - 如何对 Javascript Unix 时间戳数组进行排序

python - 为什么 Django 中没有 response_finished 信号?

python - 如何在 Python 中捕获 EINTR?