gpt4 book ai didi

c - C程序中wait()的返回值

转载 作者:行者123 更新时间:2023-11-30 15:09:54 26 4
gpt4 key购买 nike

我正在尝试打印 wait() 函数的当前值。我从输出中想到的是,当子进程运行时,子上下文中 wait() 的当前值为 -1,一旦完成并返回,则父上下文中 wait() 的值等于其子进程的 pid。根据我的理解,这个含义是否正确?

#include<stdio.h>
#include<stdlib.h>

int main ()

{
int statloc;
int stat;
printf("\nthis process id is %d", getpid());

int pid;
pid =fork();
stat=wait(&statloc);

printf("\n Value of stat is %d",stat);
getchar();
}

输出:

       this process id is 10740
Value of stat is -1k // k is entered as input due to getchar
this process id is 10740
Value of stat is 10741j // j is entered as input due to getchar

最佳答案

我认为你的理解是错误的。

wait 的用途是等待任何一个子进程退出。如果子进程退出,它返回退出子进程的进程ID,并将进程的退出状态存储在等待函数传递的参数中。

我们可以使用 WEXITSTATUS() 宏获取退出状态。

在该宏中,我们必须传递传递给 wait 系统调用的参数。如果我们通过它,它将返回进程的真实退出状态。

要了解有关等待的更多信息,请阅读以下链接。

http://man7.org/linux/man-pages/man2/wait.2.html

关于c - C程序中wait()的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36475378/

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