-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathunix_process_5.c
48 lines (44 loc) · 1.1 KB
/
unix_process_5.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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
int main(int argc, char* argv[]) {
int fd[2];
if (pipe(fd) == -1) {
printf("An error ocurred with opening the pipe\n");
return 1;
}
int id = fork();
if (id == -1) {
printf("An error ocurred with fork\n");
return 2;
}
if (id == 0) {
// Child process
close(fd[0]);
int x;
printf("Input a number: ");
scanf("%d", &x);
if (write(fd[1], &x, sizeof(int)) == -1) {
printf("An error ocurred with writing to the pipe\n");
return 3;
}
close(fd[1]);
} else {
// Parent process
close(fd[1]);
int y;
if (read(fd[0], &y, sizeof(int)) == -1) {
printf("An error ocurred with reading from the pipe\n");
return 4;
}
printf("Got from child process %d\n", y);
y = y * 3;
printf("Result is %d\n", y);
close(fd[0]);
}
return 0;
}