【问题标题】:signal handling on background process and file output后台进程和文件输出的信号处理
【发布时间】: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 将列出信号名称/编号。

标签: c unix signals fork


【解决方案1】:

您似乎正在捕获SIGTERM,然后发送SIGKILL,您没有处理程序。如果您使用 kill -TERM $pid 而不是 kill -KILL,您可能会看到预期的输出。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-08
    • 2019-06-19
    • 1970-01-01
    • 2018-06-30
    • 2020-09-04
    • 2012-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多