Writing to parent process through pipe from multiple children

907 Views Asked by At

Here's my code for the situation. Basically, I've got a number of children and they're supposed to count up a certain number of points from ptList, pass the respective points to the parent, and the parent adds them up. Unfortunately, with my printfs, the "addToTotal" variable isn't updating past the first child and my answer is incorrect. Any advice would be incredible.

pid_t worker[ workers ];
for (int i = 0; i < workers; i++) {
//printf( "I am child %i\n", i );
if ((worker[i] = fork()) < 0) {
   fail( "Can't create child");
} else if ( worker[i] == 0) {
   //Close the reading end of the pipe for each child
   close( pfd[0] );

   // Get each of the workers to compare points
   for ( int k = i; k < ptCount; k += workers ) {
      for ( int j = k + 1; j < ptCount; j++) {
        int dx = ptList[ k ].x - ptList[ j ].x;
        int dy = ptList[ k ].y - ptList[ j ].y;
        if ( dx * dx + dy * dy <= dsq )
           childTotal++;
      }
   }
   printf( "Child %i total: %i\n", i, childTotal );
   lockf( pfd[ 1 ], F_LOCK, 0 );
   write( pfd[ 1 ], &childTotal, sizeof( childTotal ));
   lockf( pfd[ 1 ], F_ULOCK, 0 );
   close( pfd[ 1 ] );
   exit(0);
   wait(NULL);
}
wait(NULL);
close( pfd[ 1 ] );
read( pfd[ 0 ], &addToTotal, sizeof( addToTotal ) );
printf( "AddToTotal: %i\n", addToTotal );
total += addToTotal;
}
2

There are 2 best solutions below

0
William Pursell On

On the first iteration of the loop, the parent closes the write side of the pipe. On the second iteration, the child inherits a pipe on which the write side is closed. You can't close the write side inside the loop, so you'll need to have a second loop to do the reads.

0
4pie0 On

The child gets a pipe on which the write side is closed, because you close it expliciltly in the line:

close( pfd[ 1 ] );

and then in the next iteration you try to write to pipe again:

write( pfd[ 1 ], &childTotal, sizeof( childTotal ));