(Please Use C programming Language to solve) ProgramA (Warming up) Create a prog
ID: 3879597 • Letter: #
Question
(Please Use C programming Language to solve)
ProgramA
(Warming up)
Create a program that reads the following set numbers: 2, 3, 7, 1, 10, 6 and store these numbers into an array. The program (parent) should create a child (slave) and send thearray to the child. The child will compute the summation of its array and wil return the summation to its parent. Finally, the parent will print the final result using the standard output (printf).
Example of execution and expected outcome.
>>./ProgramA
>I am the parent with process ID:XXX
>>I am the child with process ID:XXX and I am sending 27 to my parent
>>I am the parent with process ID:XXX with a final sum of 27
Explanation / Answer
Answer:
code:
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
int main() {
pid_t pid; //Declaring pid
pid = fork(); //The child process is forked
int summation = 0; //sumation is declared and initialized to 0 here
int arrVar[] = {2, 3, 7, 1, 10, 6}; //Declaring an array with some values in it
if (pid < 0) { // In case of an error
fprintf(stderr, "the fork is failed");
return 1; //Exit
}
else if (pid == 0) { // This is the child process
int i=0;
for (i=1; i<10; i=i+2) {
summation = summation + arrVar[i]; //The child process is calculating the summation
}
return summation;
}
else { //This is the parent process
wait(NULL); // Parent is wating for the child process to complete
int i=0;
for (i=1; i<10; i=i+2) {
summation = summation + arrVar[i];
}
printf("%d ", summation);
}
return 0;
}
Please provide your valuable feedback.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.