Tung Pham
Tung Pham

Reputation: 599

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. the program stops when the number=0. I use 2 pipes to communicate between parent and child process.

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. other processes dont have a chance. How can I fix that? thank in advance

Upvotes: 1

Views: 920

Answers (1)

William Pursell
William Pursell

Reputation: 212524

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.

Upvotes: 1

Related Questions