3.1 方法1:通过fcntl函数设置fd的属性,使其成为非阻塞IO
head.h
1 /*1方法:.通过fcntl函数设置fd的属性,使其成为非阻塞IO 2 * */ 3 #ifndef __HEAD_H__ 4 #define __HEAD_H__ 5 6 #include <stdio.h> 7 #include <stdlib.h> 8 #include <string.h> 9 #include <unistd.h> 10 #include <sys/socket.h> 11 #include <sys/types.h> 12 #include <unistd.h> 13 #include <fcntl.h> 14 #include <error.h> 15 #include <errno.h> 16 17 #define error_exit(_errmsg_) error(EXIT_FAILURE, errno, _errmsg_) 18 19 20 #endif
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
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 if (-1 == (fd = open("myfifo", O_WRONLY))) 11 error_exit("fail to open"); 12 13 while (1) 14 { 15 fgets(buff, sizeof(buff), stdin); 16 write(fd, buff, strlen(buff)+1); 17 } 18 19 return 0; 20 }
read.c
1 #include "head.h" 2 int main(void) 3 { 4 int fd = 0; 5 char buff1[1024] = {0}; 6 char buff2[1024] = {0}; 7 int flags = 0; 8 9 if ((-1 == mkfifo("myfifo", 0644)) && errno != EEXIST) 10 error_exit("fail to mkfifo"); 11 if (-1 == (fd = open("myfifo", O_RDONLY | O_NONBLOCK))) 12 error_exit("fail to open"); 13 /* 14 if (-1 == (fd = open("myfifo", O_RDONLY))) 15 error_exit("fail to open"); 16 17 flags=fcntl(fd,F_GETFL); 18 flags|=O_NONBLOCK; 19 fcntl(fd,F_SETFL,flags); 20 */ 21 22 flags = fcntl(0, F_GETFL); //F_GETFL:读取文件状态标志 23 flags = flags | O_NONBLOCK;//非阻塞 24 fcntl(0, F_SETFL, flags); //F_SETFL: 设置文件状态标志 25 26 while (1) 27 { 28 if (0 < read(fd, buff1, sizeof(buff1))) 29 printf("fifo: %s\n", buff1); 30 31 if (NULL != fgets(buff2, sizeof(buff2), stdin)) 32 printf("stdin: %s\n", buff2); 33 } 34 return 0; 35 } 36 37 /* 38 #include <unistd.h> 39 #include <fcntl.h> 40 41 int fcntl(int fd, int cmd, ... / arg / ); 42 //设置fd的属性 43 //fd/操作的命令和方式/参数 44 45 一. F_DUPFD :复制文件描述词 。 46 二. FD_CLOEXEC :设置close-on-exec标志。如果FD_CLOEXEC位是0,执行execve的过程中,文件保持打开。反之则关闭。 47 三. F_GETFD :读取文件描述词标志。 48 四. F_SETFD :设置文件描述词标志。 49 五. F_GETFL :读取文件状态标志。 50 六. F_SETFL :设置文件状态标志。 51 其中O_RDONLY, O_WRONLY, O_RDWR, O_CREAT, O_EXCL, O_NOCTTY 和 O_TRUNC不受影响, 52 可以更改的标志有 O_APPEND,O_ASYNC, O_DIRECT, O_NOATIME 和 O_NONBLOCK。 53 */

浙公网安备 33010602011771号