linux进程通信(三)--FIFO
1. /*fifoserver.c:向FIFO中写入信息*/
2. #include <sys/types.h>
3. #include <sys/stat.h>
4. #include <errno.h>
5. #include <fcntl.h>
6. #define FIFO_SERVER "FIFO4"
7. main(int argc,char** argv)
8. {
9. int fd=0;
10. char w_buf[4096];
11. int real_wnum;
12. memset(w_buf,0,4096);
13. if((mkfifo(FIFO_SERVER,O_CREAT|O_EXCL|0666)<0)&&(errno!=EEXIST))
14. printf("cannot create fifoserver\n");
15. /*此处存在着打开依赖,即若没有读端打开FIFO的话,写端就阻塞在写端*/
16. fd=open(FIFO_SERVER,O_WRONLY);
17. if(fd==-1)
18. printf("open error; no reading process\n");
19. printf("%d\n",fd);
20.
21. real_wnum=write(fd,w_buf,2048);
22. if(real_wnum==-1)
23. printf("write to fifo error; try later\n");
24. else
25. printf("real write num is %d\n",real_wnum);
26. /*往FIFO写入的数据都是原子的,如果没有足够的空间,则会等待,而不是一点一点的写入。*/
27. real_wnum=write(fd,w_buf,4096);
28. if(real_wnum==-1)
29. printf("write to fifo error; try later\n");
30. else
31. printf("real write num is %d\n",real_wnum);
32. }
1. /*fifoclient.c:从FIFO中读出数据*/
2. #include <sys/types.h>
3. #include <sys/stat.h>
4. #include <errno.h>
5. #include <fcntl.h>
6. #define FIFO_SERVER "FIFO4"
7. main(int argc,char** argv)
8. {
9. char r_buf[4096];
10. int fd;
11. int r_size;
12. int ret_size;
13. r_size=atoi(argv[1]);
14. memset(r_buf,0,sizeof(r_buf));
15. fd=open(FIFO_SERVER,O_RDONLY);
16. if(fd==-1)
17. {
18. printf("open %s for read error\n");
19. exit(1);
20. }
21. printf("%d\n",fd);
22.
23. while(1)
24. {
25. ret_size=read(fd,r_buf,r_size);