-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpoll.c
57 lines (45 loc) · 965 Bytes
/
poll.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
#define TIMES 50
void error(const char * msg);
int main(){
int pipefds[2];
if(-1 == pipe(pipefds)){
error("failed to pipe");
}
pid_t pid;
if((pid = fork()) < 0){
error("failed to fork");
}
if(pid = 0) // child
{
printf("child is running");
close(pipefds[0]);
for( int i = 0;i < Times;i++){
write(pipefds[1],"child is write",strlen("child is write");
sleep(1);
}
}
else{ //parent
printf("parent is running");
char buf[256];
close(pipefds[1]);
struct pollfd pf[2];
pf[0].fd = 0;
pf[0].events = POLLIN;
pf[1].fd = pipefds[0];
pf[1].events = POLLIN;
for(int i = 0;i < Times;i++){
poll(pf,2,500);
printf("Testing ....");
if(pf[1].revents & POLLIN){
buf[ read(pipefds[0],buf,256) ] = '\0';
printf("%s\n",buf);
}
if(pf[0].revents & POLLIN){
buf[ read(pipefds[0],buf,256) ] = '\0';
printf("%s\n",buf);
}
}
int status;
wait(&status);
}
}