int有三種型別的描述符型別:readset、writeset、exceptset,分別對應讀、寫、異常條件的描述符集合。fd_set 使用陣列實現,陣列大小使用 fd_setsize 定義。select(int n, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout);
timeout 為超時引數,呼叫 select 會一直阻塞直到有描述符的事件到達或者等待的時間超過 timeout。
成功呼叫返回結果大於 0,出錯返回結果為 -1,超時返回結果為 0。
select使用例項
服務端
1 #include 2 #include 3 #include in.h>view code4 #include 5 #include 6 #include 7 #include 8 #include 9 #include 10 #include
11 #include 12
#define default_port 6666
13int main( int argc, char **ar**)
22 printf("
socket ok \n");
23 my_addr.sin_family=af_inet;
24 my_addr.sin_port=htons(default_port);
25 my_addr.sin_addr.s_addr =inaddr_any;
26 bzero(&(my_addr.sin_zero), 0
);27
if (bind(serverfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr )) == -1
) 31 printf("
bind ok \n");
32if (listen(serverfd, lisnum) == -1
) 36 printf("
listen ok \n");
3738 fd_set client_fdset; /*
監控檔案描述符集合
*/39
int maxsock; /*
監控檔案描述符中最大的檔案號
*/40
struct timeval tv; /*
超時返回時間
*/41
int client_sockfd[5]; /*
存放活動的sockfd
*/42 bzero((void*)client_sockfd,sizeof
(client_sockfd));
43int conn_amount = 0; /*
用來記錄描述符數量
*/44 maxsock =serverfd;
45char buffer[1024
];46
int ret=0;47
while(1)61
}62/*printf("put sockfd in fdset!\n");
*/63
/*select函式
*/64 ret = select(maxsock+1, &client_fdset, null, null, &tv);
65if(ret < 0)69
else
if(ret == 0)73
/*輪詢各個檔案描述符
*/74
for(int i = 0; i < conn_amount; ++i)
85else88}
89}90/*
檢查是否有新的連線,如果收,接收連線,加入到client_sockfd中
*/91
if(fd_isset(serverfd, &client_fdset))
100/*
把連線加入到檔案描述符集合中
*/101
if(conn_amount < 5
)114 printf("
recv : %s\n
",buffer);
115if(sock_client >maxsock)
118else
122}
123}
124}
125for(int i = 0; i < 5; ++i)
129}
130close(serverfd);
131return
0;
132 }
客戶端
1 #include 2 #include 3 #includeview code4 #include 5 #include 6 #include 7 #include in.h>
8 #include 9 #include 10
#define default_port 6666
11int main( int argc, char *ar**)
19 client.sin_family =af_inet;
20 client.sin_port =htons(default_port);
21 client.sin_addr.s_addr = inet_addr(ar**[1
]);22 connfd = socket(af_inet, sock_stream, 0
);23
if(connfd < 0)27
if(connect(connfd, (struct sockaddr*)&client, sizeof(client)) < 0)31
char buffer[1024
];32 bzero(buffer,sizeof
(buffer));
33 recv(connfd, buffer, 1024, 0
);34 printf("
recv : %s\n
", buffer);
35 bzero(buffer,sizeof
(buffer));
36 strcpy(buffer,"
this is client!\n");
37 send(connfd, buffer, 1024, 0
);38
while(1)46
close(connfd);
47return0;
48 }
IO多路復用 select
select系統呼叫的目的是 在一段指定時間內,監聽使用者感興趣的檔案描述符上的可讀 可寫和異常事件。poll和select應該被歸類為這樣的系統 呼叫,它們可以阻塞地同時探測一組支援非阻塞的io裝置,直至某乙個裝置觸發了事件或者超過了指定的等待時間 也就是說它們的職責不是做io,而是幫助 呼叫者尋...
IO多路復用 select
出自朱有鵬老師的課堂 include include include include include include include include include int main void 當前有兩個fd,乙個是fd乙個是0 處理 myset fd zero myset 全部清零 fd set ...
IO多路復用 select模型
客戶端 見 c s通訊 伺服器阻塞型使用 伺服器端 include include include include include include include include include include include include int main set local address m...