- #include<fcntl.h>
- #include<stdio.h>
- #include<unistd.h>
- #include<sys/select.h>
- #include<sys/types.h>
- #include<sys/time.h>
- #define PIPENAME "/tmp/p1"
- #define PIPENAME_TWO "/tmp/p2"
- #define MSGCOUNT 10
- #define MSGSIZE 255
- /*管道1,2的文件描述符*/
- int fd1,fd2;
- pid_t pid1,pid2;
- int
- main(int argc,char *argv[]) {
- char buf[255],buf2[255];
- int len,rfd;
- struct timeval val;
- fd_set set;
- /*創建管道1,並打開*/
- if(mkfifo(PIPENAME,O_CREAT|O_EXCL)<0) /*創建管道1*/
- {
- perror("Create1 error!\n");
- unlink(PIPENAME);/*清除管道1*/
- exit(0);
- }
- fd1=open(PIPENAME,O_RDWR,0);/*打開管道1*/
- if(fd1<0)
- {
- perror("open1 error!\n");
- unlink(PIPENAME);
- exit(0);
- }
- /*創建管道2,並打開*/
- if(mkfifo(PIPENAME_TWO,O_CREAT|O_EXCL)<0) /*創建管道2*/
- {
- perror("Create2 error!\n");
- unlink(PIPENAME_TWO);/*清除管道2*/
- exit(0);
- }
- fd2=open(PIPENAME_TWO,O_RDWR,0);/*打開管道2*/
- if(fd2<0)
- {
- perror("open2 error!\n");
- unlink(PIPENAME_TWO);
- exit(0);
- }
- /*******創建2個子進程********/
- pid1=fork();
- if(pid1==0)/*子進程*/
- {
- char msg[]="hello";
- sleep(4);
- printf("write to Pipe2\n");
- write(fd2,msg,sizeof(msg));
- }
- else
- {
- pid2=fork();
- if(pid2==0)/*子進程*/
- {
- char msg[]="hello";
- sleep(5);
- printf("write to Pipe1\n");
- write(fd1,msg,sizeof(msg));
- }
- /*超時時間*/
- val.tv_sec=5;
- val.tv_usec=0;
- while(1)
- {
- /*設置文件描述符集,先清空,再加入管道1,2*/
- /*每次循環都要清空集合,否則不能檢測描述符變化 */
- FD_ZERO(&set);
- FD_SET(fd1,&set);
- FD_SET(fd2,&set);
- rfd=select(FD_SETSIZE,&set,NULL,NULL,&val);
- switch(rfd)
- {
- case -1: exit(-1);break;
- case 0:break;
- default:
- if(FD_ISSET(fd1,&set)) //測試fd1是否可讀,
- {
- read(fd1,buf2,sizeof(buf2));
- printf("[1]Get msg!\n");
- }
- if(FD_ISSET(fd2,&set))
- {
- read(fd2,buf,sizeof(buf));
- printf("[2]Get msg!\n");
- }
- }//switch
- }//while
- }//else
- } //main
write to Pipe2
[2]Get msg!
write to Pipe1
[1]Get msg!