gpt4 book ai didi

c - waitpid 用法错误?

转载 作者:太空宇宙 更新时间:2023-11-04 06:37:14 25 4
gpt4 key购买 nike

我试图从父进程访问 fork 子进程的退出状态,但我得到了奇怪的答案。有时,我得到 256,有时我得到一个负数,这取决于我指定的是 &status 还是仅指定 status。我知道我真的很接近。有人可以为我提供一点帮助,我将如何获得 EXIT_STATUS

这是我的代码

pid_t  pid;
int *status;
if((pid = fork()) < 0)
fprintf(stdout, "Error forking child process\n");

else if (pid == 0)
{
execvp(input[0], input);
fprintf(stdout, "Invalid process!!\n");
_exit(EXIT_FAILURE);

}
else
{
while (waitpid(-1, status, 0) != pid);
fprintf(stdout, "The status is %d\n", &status);
}

最佳答案

您看到此行为是因为您没有初始化正在使用的指针,因此您正在调用未定义的行为,这意味着,从字面上看,任何事情 可能会发生。尝试将 status 更改为 int(而不是 int*):

int status;
/* ... */
while (waitpid(-1, &status, 0) != pid);
fprintf(stdout, "The status is %d\n", status);

另一方面,您的代码:

int * status;

这会创建一个指向 int 的指针,但不会对其进行初始化。

while (waitpid(-1, status, 0) != pid);

在这里,您将此指针传递给 waitpid(),它将在 指向的位置。由于你还没有初始化 指针,它正在写入一个未指定内存 地点!这可能会使进程崩溃或覆盖 在别处分配的内存,这可能会导致 稍后自发崩溃,或数据损坏!

fprintf(stdout, "The status is %d\n", &status);

这打印出指针变量的地址——不是 它指向的值!使用 *status 而不是 &status 可能允许这部分工作,但你 仍在使用未初始化的指针。

我强烈建议您将编译器的警告设置调到最大值(通过 gcc 传递 -Wall)以使其对所有内容发出警告。它会捕捉到未初始化指针的使用,并且它可能还会警告您使用带有指针类型值的 %d 格式说明符。

关于c - waitpid 用法错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13328332/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com