C:Process如何在linux中进行通信

时间:2013-04-06 11:19:33

标签: c linux process

我想计算使用for 1,10和fork()si执行的进程数。该程序在linux中执行。我真的没有得到如何使用等待或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);

}               

1 个答案:

答案 0 :(得分:1)

进程中使用WEXITSTATUS等宏来获取wait来电后的退出状态。

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

在父级中,您使用WEXITSTATUS,如下所示:

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

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