Question: Your code will be called with command-line arguments consisting of positive integers. Do not worry about bad command-line arguments such as xyz. Your code will
Your code will be called with command-line arguments consisting of positive integers. Do not worry about bad command-line arguments such as "xyz". Your code will not be tested in this way.
The parent process will take the arguments to main(), convert them into ints by calling atoi(), and send those ints one at a time to the child process through a pipe (one call to write() for each int).
Do not send anything from argv[0] through the pipe. Start with argv[1] and continue through the rest of the arguments.
The child process will read the ints sent by the parent process one at a time, and add them up. The child process should not use the arguments to main(), argc and argv, in any way whatsoever. The child process will communicate the sum of the numbers to the parent as the return value from main().
The parent process will need to reap the child process to find out that sum.
It may be of use to know that read() will return immediately with a zero once the other end of the pipe is closed by the parent.
If I call your code this way:
a03 3 5 7
The parent process should print out:
CS201 - Assignment 3 Regular - I. Forgot sum = 15
Here is the given code, please don't change anything, just add to it.
#include
int main(int argc, char **argv) { // set up pipe
// call fork()
printf("CS201 - Assignment 3 Regular - I. Forgot ");
if (0 /* replace 0 with test for parent vs child, delete this comment */) { // -- running in child process -- int sum = 0;
// Receive numbers from parent process via pipe // one at a time, and count them.
// Return sum of numbers.
return sum;
} else { // -- running in parent process -- int sum = 0;
// Send numbers (datatype: int, 4 bytes) from command line arguments // starting with argv[1] one at a time through pipe to child process.
// Wait for child process to return. Reap child process. // Receive sum of numbers via the value returned when // the child process is reaped.
printf("sum = %d ", sum); return 0; } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
