c - Fork 子进程以信号 0 终止

标签 c signals fork

我有一个小函数,可以为我提供有关子进程如何完成的信息。

int debug_wait() {
    int status;
    wait(&status);
    if (WIFSIGNALED(status)) {
        int sig = WSTOPSIG(status);
        printf("failed with signal %d (%s)\n", sig, strsignal(sig));
        return 1;
    }
    else if (!WIFEXITED(status)) {
        printf("ended in an unexpected way\n");
        return 1;
    }
    return 0;
}

但我得到以下结果:

double free or corruption (out)
tests failed with signal 0 (Unknown signal 0)

我知道我应该修复我的代码,但为什么我收到信号号。 0?我的函数有错误还是有其他含义?

既然有人问了,这里有一个示例程序:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <string.h>

int debug_wait() {
    int status;
    wait(&status);
    if (WIFSIGNALED(status)) {
        int sig = WSTOPSIG(status);
        printf("tests failed with signal %d (%s)\n", sig, strsignal(sig));
        return 1;
    }
    else if (!WIFEXITED(status)) {
        printf("tests ended in an unexpected way\n");
        return 1;
    }
    return 0;
}

int main() {
    void* ptr = malloc(10);
    pid_t pid = fork();
    if (pid == 0) {
        free(ptr);
        free(ptr);
    }
    else {
        debug_wait();
    }
}

最佳答案

您正在解码错误的内容。如果 WIFSIGNALEDtrue,您可以使用 WTERMSIGWCOREDUMP(检查 #ifdef WCOREDUMP第一的)。要解码 WSTOPSIG,则 WIFSTOPPED 必须为 true

示例:

int status;
pid_t pid = wait(&status);
if (pid == -1) return 1;

if (WIFEXITED(status)) {
    printf("normal exit %d\n", WEXITSTATUS(status));

} else if (WIFSIGNALED(status)) {
    printf("termsig %d core dump=%c\n", WTERMSIG(status),
            WCOREDUMP(status) ? 'Y' : 'N');

} else if (WIFSTOPPED(status)) {
    printf("stop %d cont=%c\n", WSTOPSIG(status),
           WIFCONTINUED(status) ? 'Y' : 'N');
}

不使用功能测试宏:

if (WIFEXITED(status)) {
    printf("normal exit %d\n", WEXITSTATUS(status));

} else if (WIFSIGNALED(status)) {
    printf("termsig %d\n", WTERMSIG(status));

} else if (WIFSTOPPED(status)) {
    printf("stop %d\n", WSTOPSIG(status));
}

关于c - Fork 子进程以信号 0 终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74280958/

相关文章:

c - 如何将输入行协调到相关数组中

C- 服务器/客户端,等待其他客户端然后退出

linux - 如何防止我的 C 程序在按下 CTRL-C 时终止?

C编程: Fork() and IPC with Pipes

c - 一项剥夺子孙的计划

手工制作 shell 的后台问题中的子进程

c - 关于gcc中静态库的一些问题

c - 初始化分配数组的大小

python - signal.spectrogram 返回太多赫兹

c - C 中的 Gtk+ 3。无法在回调函数中正确转换