int
iffpipecfds.fi
1
exit
int result = fork();
if (result < 0) {
perror("fork");
CSC209H Worksheet: Pipes (workers & controller)
In the last worksheet we wrote a program that forked one child for each commandline argument. The child computed the length of the commandline argument and exits with that integer as the exit status. The parent sums these return codes and reports the total length of all the commandline arguments together. For this worksheet, we will do the same program, except that each child will communicate the string¡¯s length to the parent through a pipe.
int main(int argc, char **argv) {
// Declare any new variables you need
fdsLarge 2
// Write the code to loop over the command line arguments.
for (int i = 1; i < argc; i++) {
// Before we call fork, call pipe
workers
controlled
DID DID
perrorC
pipe
exit(1);
} else if (result == 0) { // child process
// Child only writes to the pipe, so close reading end
dose
fdsci
// Before we forked, parent had open the reading ends to
// all previously forked children; so close those.
forcint
Co
KI Kci Htt
closeCfds
E
KIK
write
fdg
I
sireoffutt
O
}
CSC209H Worksheet: Pipes (workers & controller)
// Now do the work - write the value in binary to the pipe
int len = strlen(argv[i]);
Glen
// Close the pipe since we are done with it.
closeCfds
exit(0); // Don¡¯t fork children on next loop iteration
} else {
// In the parent, but before doing the next loop iteration,
// close the end of the pipe that we don¡¯t want open
close Cfds }
B
// Only the parent gets here
int sum = 0;
// Read one integer from each child, print it and add to sum
int valve In forcint's
giaargcyg.tt
Co value sneoffint
sum
readCfds
value
closeCfds
printf("The length of all the args is %d\n", sum);
return 0; }
ED
Co
2
p
a
child
i
7
pipes are unidirectional