[英]How to yield a child process created by fork(), then other child processes have chance to run?
In my program, I create 3 child processes and then assign them to do a same thing which is decreasing a number. 在我的程序中,我创建了3个子进程,然后将它们分配给做同样的事情,这减少了数目。 the program stops when the number=0.
当数字= 0时,程序停止。 I use 2 pipes to communicate between parent and child process.
我使用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]);
}
My problem is there only one child process running and decreasing a value until a=0. 我的问题是只有一个子进程正在运行并减小值直到a = 0。 other processes dont have a chance.
其他过程没有机会。 How can I fix that?
我该如何解决? thank in advance
预先感谢
You want to have each child block on a read from the parent on each iteration of the loop. 您希望在每次循环迭代时都从父级读取每个子块。 For example, the child code should be something like:
例如,子代码应类似于:
while( read( p1[0], &a, sizeof a ) == sizeof a ) {
a -= 1;
write( p2[1], &a, sizeof a );
}
and the parent code should look like: 父代码应如下所示:
do {
write( p1[1], &a, sizeof a );
} while( read( p2[0], &a, sizeof a ) == sizeof a && a > 0 );
close( p1[1] );
This makes each child block on a read after decrementing the counter, thus going to sleep until the parent is scheduled. 这使每个子块在递减计数器后进行读取,从而进入睡眠状态,直到调度了父块。 After the parent writes a value into the appropriate pipe, only one of the children that is blocking on a read will be awakened to decrement the counter.
父级将值写入适当的管道后,将仅唤醒在读取过程中阻塞的子级之一以减少计数器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.