异步I/O事件处理
Posted sip-inaction
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了异步I/O事件处理相关的知识,希望对你有一定的参考价值。
异步I/O
所谓异步I/O,是指以事件触发的机制来对I/O操作进行处理;与多进程和多线程技术相比,异步I/O技术的最大优势是系统开销小,系统不必创建进程/线程,也不必维护这些进程/线程,从而减少了系统的开销。
1 /** 2 client.c 3 */ 4 #include <stdio.h> 5 #include <unistd.h> 6 #include <string.h> 7 #include <strings.h> 8 #include <sys/types.h> 9 #include <sys/socket.h> 10 #include <netinet/in.h> 11 #include <arpa/inet.h> 12 13 #define PORT 8111 14 #define MSG_LEN 1024 15 16 int main(int argc, char* argv[]) 17 { 18 if (argc != 2) { 19 printf("usage: ./%s <ipaddress> ", argv[0]); 20 return 1; 21 } 22 23 int ret = -1; 24 int socket_fd; 25 socklen_t addr_len; 26 struct sockaddr_in serv_addr; 27 char send_buf[MSG_LEN] = { 0 }; 28 char recv_buf[MSG_LEN] = { 0 }; 29 30 socket_fd = socket(AF_INET, SOCK_STREAM, 0); 31 if (socket_fd < 0) { 32 printf("create socket fd failed. "); 33 _exit(-1); 34 } 35 36 bzero(&serv_addr, sizeof(serv_addr)); 37 serv_addr.sin_family = AF_INET; 38 serv_addr.sin_port = htons(PORT); 39 serv_addr.sin_addr.s_addr = inet_addr(argv[1]); 40 addr_len = sizeof(struct sockaddr); 41 ret = connect(socket_fd, (struct sockaddr *)&serv_addr, addr_len); 42 if (ret < 0) { 43 printf("connect to server[%s:%d] failed. ", argv[1], PORT); 44 _exit(-1); 45 } 46 47 while (1) { 48 memset(send_buf, 0, sizeof(send_buf)); 49 memset(recv_buf, 0, sizeof(recv_buf)); 50 gets(send_buf); 51 52 if (strncmp(send_buf, "quit", 4) == 0) 53 break; 54 55 ret = send(socket_fd, (void *)send_buf, strlen(send_buf), 0); 56 if (ret < 0) { 57 printf("send msg[%s] failed. ", send_buf); 58 break; 59 } 60 61 ret = recv(socket_fd, (void *)recv_buf, sizeof(recv_buf), 0); 62 if (ret < 0) { 63 printf("receive zero msg. "); 64 continue; 65 } 66 67 recv_buf[ret] = ‘