-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpipe_Integer_Array.c
60 lines (47 loc) · 1.12 KB
/
pipe_Integer_Array.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main(int argc, char *argv[])
{
int *arr = (int *)malloc((argc - 1) * sizeof(int));
// printf("\nArray from Terminal: ");
for (int i = 0; i < argc - 1; i++)
{
arr[i] = atoi(argv[i + 1]);
}
int fd1[2];
int fd2[2];
pipe(fd1);
pipe(fd2);
pid_t pid = fork();
if (pid == 0)
{
close(fd1[1]);
close(fd2[0]);
int receivedArr[100];
read(fd1[0], receivedArr, sizeof(receivedArr));
close(fd1[0]);
int sum = 0;
for (int i = 0; i < argc - 1; i++)
{
sum = sum + receivedArr[i];
}
write(fd2[1], &sum, sizeof(sum));
close(fd2[1]);
}
else
{
close(fd1[0]);
close(fd2[1]);
// Send array to child
write(fd1[1], arr, (argc - 1) * sizeof(int));
close(fd1[1]);
int sum;
read(fd2[0], &sum, sizeof(sum));
close(fd2[0]);
printf("The sum of the array is %d\n", sum);
wait(NULL); // Wait for the child to finish
}
return 0;
}