-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpipe_example.c
More file actions
47 lines (43 loc) · 1006 Bytes
/
pipe_example.c
File metadata and controls
47 lines (43 loc) · 1006 Bytes
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
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
#define BUFSIZE (10)
int main(int argc, char* argv[])
{
int pipefds[2];
pid_t pid;
char buf[BUFSIZE];
//create pipe
if(pipe(pipefds) == -1){
perror("pipe");
exit(EXIT_FAILURE);
}
memset(buf,0,BUFSIZE);
pid = fork();
if (pid == 0) {
//child close the write end
close(pipefds[1]);
//child read from the pipe read end until the pipe is empty
while(read(pipefds[0], buf, 1)==1){
buf[1] = '\0';
printf("CHILD read from pipe -- %s\n", buf);
}
//after finishing reading, child close the read end
close(pipefds[0]);
printf("CHILD: EXITING!\n");
exit(EXIT_SUCCESS);
}else {
printf("PARENT write in pipe\n");
//parent close the read end
close(pipefds[0]);
//parent write in the pipe write end
write(pipefds[1], "UICCS361", 8);
//after finishing writing, parent close the write end
close(pipefds[1]);
//parent wait for child
wait(NULL);
}
return 0;
}