我有一个小函数,可以为我提供有关子进程如何完成的信息。
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();
}
}
最佳答案
您正在解码错误的内容。如果 WIFSIGNALED
为 true
,您可以使用 WTERMSIG
和 WCOREDUMP
(检查 #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/