-
Notifications
You must be signed in to change notification settings - Fork 0
/
13_Unnamed_Pipe_Exponentiation.c
73 lines (58 loc) · 1.51 KB
/
13_Unnamed_Pipe_Exponentiation.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
61
62
63
64
65
66
67
68
69
70
71
72
73
// Q. Create an unnamed pipe for inter-process communication.
// Accept 2 integers x, y in the child process and
// pass it to parent process to calculate x^y and pass it back to
// child process to print it.
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main()
{
int f, fd[2], len;
int arr[3] = {-1, -1, 1};
pipe(fd);
f = fork();
// The creation of the process was unsuccessful
if (f < 0)
{
printf("Error occurred!\n");
}
// Child process
else if (f == 0)
{
// For runtime input
char data[50];
printf("Enter the base: ");
scanf("%d", &arr[0]);
printf("Enter the power: ");
scanf("%d", &arr[1]);
printf("Child: Passing the data to Parent.\n");
write(fd[1], arr, sizeof(arr)); // Send data to parent
sleep(5);
read(fd[0], arr, sizeof(arr)); // Received result from parent
printf("Result: %d to the power %d is %d.\n", arr[0], arr[1], arr[2]);
}
// Parent process
else
{
read(fd[0], arr, sizeof(arr)); // Received data from child
printf("Parent: Data received.\n");
// Exponentiation
for (int i = 1; i <= arr[1]; i++)
{
arr[2] *= arr[0];
}
printf("Parent: Passing the result to child.\n");
write(fd[1], arr, sizeof(arr)); // Send the result to child
}
}
/*
Output:
s4shibam@SHIBAM:~/OS$ gcc 13_Unnamed_Pipe_Exponentiation.c
s4shibam@SHIBAM:~/OS$ ./a.out
Enter the base: 5
Enter the power: 4
Child: Passing the data to Parent.
Parent: Data received.
Parent: Passing the result to child.
s4shibam@SHIBAM:~/OS$ Result: 5 to the power 4 is 625.
*/