forked from yuebaixiao/network
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocess-17-pipe.cpp
More file actions
56 lines (47 loc) · 939 Bytes
/
process-17-pipe.cpp
File metadata and controls
56 lines (47 loc) · 939 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
47
48
49
50
51
52
53
54
55
56
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <wait.h>
int main(){
int p[2];
pid_t pid;
char buf[1024];
memset(buf, 0, sizeof(buf));
if(pipe(p) != 0){
perror("pipe");
return 1;
}
pid = fork();
if(pid < 0){
perror("fork");
return 1;
}
if(pid == 0){
printf("child process : my_id=%d\n",getpid());
close(p[0]);
dup2(p[1], fileno(stdout));
char *argv[ ]={"ls", "/home/ys/cpp/network"};
if(execve("/bin/ls", argv, NULL) < 0){
perror("exec");
return 1;
}
exit(0);
}else{
int n;
FILE* filep;
close(p[1]);
printf("parent process : child process id=%d\n", pid);
filep = fdopen(p[0], "r");
if(filep == NULL){
perror("fdopen");
return 1;
}
while(fgets(buf, sizeof(buf), filep) != NULL){
printf("get:%s\n", buf);
}
int status;
wait(&status);
}
return 0;
}