3.0 阻塞IO

head.h

 1 /*
 2  *阻塞IO
 3  * */
 4 #ifndef __HEAD_H__
 5 #define __HEAD_H__
 6 
 7 #include <stdio.h>
 8 #include <stdlib.h>
 9 #include <string.h>
10 #include <sys/socket.h>
11 #include <sys/types.h>
12 #include <unistd.h>
13 #include <sys/stat.h>
14 #include <fcntl.h>
15 #include <error.h>
16 #include <errno.h>
17 
18 #define error_exit(_errmsg_)    error(EXIT_FAILURE, errno, _errmsg_);
19 
20 #endif
21 /*
22  * 标准IO:有缓存,效率高,处理速度低
23  *         fgetc fputc fread
24  *         fgets fputs fwrite
25  * 文件IO:无缓存,效率低,处理速度高,仅基于linux下
26  *         write read
27  */

Makefile

1 ALL: r w
2 
3 r:read.c
4     gcc $< -o $@
5 w:write.c
6     gcc $< -o $@
7 .PHONY:
8 clean:
9     rm r w

read.c

 1 #include "head.h"
 2 
 3 int main(void)
 4 {
 5     int fd = 0;
 6     char buff[1024] = {0};
 7 
 8     if (-1 == mkfifo("myfifo", 0644) && errno != EEXIST)
 9         error_exit("fail to mkfifo");
10 
11     if (-1 == (fd = open("myfifo", O_RDONLY)))
12         error_exit("fail to open");
13 
14     while (1)
15     {
16         read(fd, buff, sizeof(buff));
17         printf("fifo:%s\n", buff);
18 
19         fgets(buff, sizeof(buff), stdin);
20         printf("stdin:%s\n", buff);
21     }
22 
23     return 0;
24 }

write.c

 1 #include "head.h"
 2 
 3 int main(void)
 4 {
 5     int fd = 0;
 6     char buff[1024] = {0};
 7 
 8     if ((-1 == mkfifo("myfifo", 0644)) && errno != EEXIST)
 9         error_exit("fail to mkfifo");
10     
11     if (-1 == (fd = open("myfifo", O_WRONLY)))
12         error_exit("fail to open");
13     while (1)
14     {
15         fgets(buff, sizeof(buff), stdin);
16         write(fd, buff, strlen(buff)+1);
17     }
18 
19     return 0;
20 }

 

posted @ 2017-03-13 21:26  bkycrmn  阅读(107)  评论(0)    收藏  举报