gpt4 book ai didi

C:Linux中进程如何通信

转载 作者:行者123 更新时间:2023-11-30 19:22:34 25 4
gpt4 key购买 nike

我想计算使用 for 1,10 创建的进程数以及执行 fork() si 的进程数。该程序在linux下执行。我真的不知道如何使用 wait 或 WEXITSTATUS,并且我在论坛上花了几个小时,但仍然不明白。有人可以帮我吗?

谢谢,德拉戈斯

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

int nr = 1;

int main()
{


int pid;
int i;
int stare;
for(i = 1; i<=10 ; i++)
{

pid = fork();

if( pid !=0 )
{

//parent
wait(&stare);
nr = nr + stare;


}
else
{
//child
nr++;
stare = WEXITSTATUS(nr);
exit(nr);

}
}

printf("\nNr: %d\n", nr);

}

最佳答案

诸如 WEXITSTATUS 之类的宏在进程中使用,以在 wait 调用后获取退出状态。

在子进程中,只需返回nr(或使用它作为参数调用exit)就足够了。

在父级中,您可以像这样使用WEXITSTATUS:

if (wait(&stare) > 0)
{
if (WIFEXITED(stare))
nr += WEXITSTATUS(stare);
}

我们必须使用 WIFEXITED 检查,否则退出状态无效。

关于C:Linux中进程如何通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15850258/

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