c - 如何yield一个fork()创建的子进程,让其他子进程有机会运行?

标签 c linux multiprocessing fork pipe

在我的程序中,我创建了 3 个子进程,然后分配它们做同样的事情,即减少一个数字。当 number=0 时程序停止。我使用 2 个管道在父进程和子进程之间进行通信。

int  a;
int main(void)
{

a=10;
//declare and create 2 pipes
int p1[2], p2[2];
pipe(p1);
pipe(p2);
    int ra;
for(int i=0;i<3;i++)
{   
    pid=fork();
    if(pid==0) 
    {
        close(p1[1]);
        close(p2[0]);
        read(p1[0],&ra,3);

        while(ra>0)
        {

            ra-=1;
            printf("%i a are available, reported by process %i\n",ra,getpid());
            close(p1[0]);
            write(p2[1],&ra,3);

            close(p2[1]);

        }
        break;

    }
    else
    if(pid>0)
    {


    }else
    {
        wait(NULL);

    }

}
  }
 if(pid>0)
{
        close(p1[0]);
        close(p2[1]);
        if(a>0)
        {
            write(p1[1],&a,3);
            close(p1[1]);
        }
        else
            exit(0);
        read(p2[0],&ra,3);
        a=ra;
        close(p2[0]);


}

我的问题是只有一个子进程在运行并递减一个值直到 a=0。其他进程没有机会。 我该如何解决?提前致谢

最佳答案

您希望在循环的每次迭代中从父 block 读取每个子 block 。例如,子代码应该是这样的:

while( read( p1[0], &a, sizeof a ) == sizeof a ) {
  a -= 1;
  write( p2[1], &a, sizeof a );
}

父代码应该是这样的:

do {
    write( p1[1], &a, sizeof a );
} while( read( p2[0], &a, sizeof a ) == sizeof a && a > 0 );
close( p1[1] );

这使得每个子进程在递减计数器后阻塞读取,从而进入休眠状态直到父进程被调度。在父级将一个值写入适当的管道后,只有阻塞读取的子级之一会被唤醒以减少计数器。

关于c - 如何yield一个fork()创建的子进程,让其他子进程有机会运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19372675/

相关文章:

linux - & 在 shell 代码脚本中将 stderr 重定向到 stdout (2>&1) 是什么意思?

linux - 查找:-exec 缺少参数不复制

php - 更改文件和文件夹权限后出现 403 Forbidden

Python 多处理进程类生命周期

c++ - 无法获取输出 union 集

c - 将数组传递给已扫描的函数

Python Tkinter 多处理进展

callback - 是否可以向 ZeroMQ 添加事件处理以在接收/发送数据时进行操作?

c - 将名称添加到多重链接列表中

在 C ( linux ) 中捕获鼠标事件