3.2 方法2:异步IO方式解决阻塞IO问题
head.h
1 //方法2:异步IO方式解决阻塞IO问题 2 #ifndef _HEAD_H_ 3 #define _HEAD_H_ 4 5 #include <stdio.h> 6 #include<stdlib.h> 7 #include<string.h> 8 #include<error.h> 9 #include<errno.h> 10 #include<sys/types.h> 11 #include<sys/socket.h> 12 #include<netinet/in.h> 13 #include<netinet/ip.h> 14 #include<arpa/inet.h> 15 #include<signal.h> 16 #include<sys/stat.h> 17 #include<fcntl.h> 18 #define error_exit(_errmsg_) error(EXIT_FAILURE,errno,_errmsg_) 19 #define SER_PORT 50000 20 #define SER_ADDR "192.168.1.104" 21 22 #endif
Makefile
1 ALL:r w 2 r:read.c 3 gcc $< -o $@ 4 w:write.c 5 gcc $< -o $@ 6 .PHONY: 7 clean: 8 rm r w
write.c
1 #include"head.h" 2 int main()//write 3 { 4 int fd=0; 5 char buff[1024]={0}; 6 7 if((-1==mkfifo("myfifo",0644))&&errno!=EEXIST) 8 error_exit("fail to mkfifo!"); 9 if(-1==(fd=open("myfifo",O_WRONLY))) 10 error_exit("fail to open!"); 11 12 while(1) 13 { 14 fgets(buff,sizeof(buff),stdin); 15 write(fd,buff,strlen(buff)+1); 16 } 17 return 0; 18 }
read.c
1 #include"head.h" 2 char buff[1024]={0}; 3 int fd=0; 4 void handler(int signo)// 5 { 6 read(fd,buff,sizeof(buff)); 7 printf("fifo:%s\n",buff); 8 return ; 9 } 10 11 int main()//read 12 { 13 int flags=0; 14 15 if(SIG_ERR==signal(SIGIO,handler))// 16 error_exit("fail to signal!"); 17 if((-1==mkfifo("myfifo",0644))&&errno!=EEXIST) 18 error_exit("fail to mkfifo!"); 19 //异步IO/ 29/SIGIO 20 if(-1==(fd=open("myfifo",O_RDONLY))) 21 error_exit("fail to open!"); 22 23 flags=fcntl(fd,F_GETFL); 24 flags=flags|O_ASYNC;//设置为异步方式 25 fcntl(fd,F_SETFL,flags); 26 27 fcntl(fd,F_SETOWN,getpid());// 28 29 while(1) 30 { 31 //自己在终端输入和打印 32 fgets(buff,sizeof(buff),stdin); 33 printf("stdin:%s\n",buff); 34 } 35 return 0; 36 } 37 /* 38 八. 信号管理 39 F_GETOWN, F_SETOWN, F_GETSIG 和 F_SETSIG 被用于IO可获取的信号。 40 41 F_GETOWN:获取当前在文件描述词 fd上接收到SIGIO 或 SIGURG事件信号的进程或进程组标识 。 42 43 F_SETOWN:设置将要在文件描述词fd上接收SIGIO 或 SIGURG事件信号的进程或进程组标识 。 44 45 F_GETSIG:获取标识输入输出可进行的信号。 46 47 F_SETSIG:设置标识输入输出可进行的信号。 48 49 使用以上命令,大部分时间程序无须使用select()或poll()即可实现完整的异步I/O。 50 */

浙公网安备 33010602011771号