-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpipe_string.c
More file actions
93 lines (51 loc) · 1.37 KB
/
pipe_string.c
File metadata and controls
93 lines (51 loc) · 1.37 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#define MAX 101
void read_pipe(int * fd, char * buff, int buff_size){
int char_count;
while((char_count = read(fd[0], buff, buff_size)) != 0){ // read data when available
if(strcmp(buff,"q\n") == 0){
printf("Child Exiting\n");
break;
}
printf("Child read : %s",buff); // print read data
}
}
void write_pipe(int * fd, char * buff, int buff_size){
while(fgets(buff, buff_size, stdin)){ // read user input from stdin
write(fd[1], buff, buff_size); // write user input to pipe
if(strcmp(buff,"q\n") == 0){
printf("Parent Exiting\n");
break;
}
printf("Parent : enter new line(100 chars max) : q to quit\n");
}
}
int main(){
pid_t pid;
char buffer[MAX];
int fd[2]; // file descriptors to be used as pipe I/O
printf("Parent : started execution\n");
pipe(fd); // create pipe
pid = fork(); // fork child
if(pid == -1){
perror("fork");
exit(1);
}
else if(pid == 0){ // child
printf("Child : started execution\n");
close(fd[1]);
read_pipe(fd, buffer, sizeof(buffer)); // read from pipe as data is available
exit(0);
}
else{ // parent
close(fd[0]);
printf("Parent : Input string (100 chars max)\n");
write_pipe(fd, buffer, sizeof(buffer)); // write to pipe as data is entered
exit(0);
}
}