I am trying to send a value from child to parent but am not getting the desired output. Can anyone figure out what I am doing wrong?
int main() {
printf("I am the parent with process ID:%d\r\n", (int) getpid());
int rc = fork();
int sum = 0;
int array[6] = {2, 3, 7, -1, 10, 6};
int pipeNum[2];
pipe(pipeNum);
if (rc < 0) {
fprintf(stderr, "fork failed\r\n");
exit(1);
} else if (rc == 0) {
for (int i = 0; i < 6; i++) {
sum += array[i];
}
close(pipeNum[0]);
printf("I am the child with process ID:%d and I am sending %d to my parent.\r\n", (int) getpid(), sum);
write(pipeNum[1], &sum, sizeof(sum));
close(pipeNum[1]);
} else {
wait(NULL);
close(pipeNum[1]);
read(pipeNum[0], &sum, sizeof(sum));
printf("I am the parent with process ID:%d with a final sum of %d\r\n", (int) getpid(), sum);
close(pipeNum[0]);
exit(0);
}
return 0;
}
Here is the output I am getting
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 0
Any help would be appreciated