Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux管理 >> Linux 網路

Linux 網絡編程深入剖析:select I/O 多工完整指南

一、什麼是 I/O 多工

I/O 多工的核心價值,在於解決「行程或執行緒被某個 I/O 系統呼叫卡住」的問題,讓程式不必死等單一 I/O 而停擺。

常見的適用情境

1. 當客戶端需要同時管理多個描述符(例如互動式輸入與多個網絡套接字)時,I/O 多工几乎是必備手段。

2. TCP 伺服器既要照看監聽套接字,又要處理已連線的套接字,通常都會導入 I/O 多工。

3. 若伺服器同時要處理 TCP 與 UDP,導入 I/O 多工會讓架構清爽許多。

4. 需要同時對外提供多種服務時,I/O 多工同樣是理想的整合方式。

常見的多工函式有 select 與 poll,本文聚焦於 select。

二、select() 函式解析

函式原型:

int select(int maxfd, fd_set *readset, fd_set *writeset, fd_set *exceptset, const struct timeval *timeout);

它的功能是不斷掃描一批描述符,只要其中任何一個發生事件,或等待時間到,函式便會返回。各參數意義如下:

maxfd:要偵測的描述符範圍,等於集合中最大值加一。

readset:可讀集合,用來監看哪些描述符有資料可讀。

writeset:可寫集合,用來監看哪些描述符可以寫入。

exceptset:異常集合,用來監看哪些描述符發生了例外狀況。

timeout:超時時間,逾時後便喚醒。

返回值有三種:回傳 0 代表超時;回傳 -1 代表出錯;回傳大於 0 則是已就緒的描述符數量。

所需的標頭檔:

#include <sys/select.h>
#include <sys/time.h>

超時結構如下:

struct timeval{
 long tv_sec;//秒
 long tv_usec;//微秒
};

例如想等待 10.2 秒:

struct timeval timeout;
timeout.tv_sec = 10;
timeout.tv_usec = 200000;

若將 timeout 參數設為 NULL,select 便會永遠等待,直到有事件發生。

描述符集合的操作

select 之所以能同時監看大量描述符,關鍵在於它把描述符依「讀、寫、異常」三種特性分別放進三個集合,再整批交給 select 處理。要操作這些集合,需要熟悉以下四個巨集:

void FD_ZERO(fd_set *fdset);           // 清空集合
void FD_SET(int fd, fd_set *fdset);   // 加入一個描述符
void FD_CLR(int fd, fd_set *fdset);   // 移除一個描述符
int FD_ISSET(int fd, fd_set *fdset);  // 檢測某描述符是否有事件

整體使用框架

以監看描述符 0、4、5 是否可讀為例:

while(1)
{
 fd_set rset; //建立集合
 FD_ZERO(&rset); //清空
 FD_SET(0, &rset); //加入描述符 0
 FD_SET(4, &rset); //加入描述符 4
 FD_SET(5, &rset); //加入描述符 5
 
 if(select(5+1, &rset, NULL, NULL, NULL) > 0)
 {
  if(FD_ISSET(0, &rset))
  {
   //描述符 0 可讀的處理
  }
  if(FD_ISSET(4, &rset))
  {
   //描述符 4 可讀的處理
  }
  if(FD_ISSET(5, &rset))
  {
   //描述符 5 可讀的處理
  }
 }
}

三、select 的應用對比

我們以「UDP 同時收發」為例,對比多執行緒與 select 兩種寫法。直覺上,同時收發似乎得開一條執行緒收、一條執行緒發,以下先示範多執行緒版本:

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>

//接收執行緒:負責收訊並顯示
void *recv_thread(void* arg)
{
 int udpfd = (int)arg;
 struct sockaddr_in addr;
 socklen_t addrlen = sizeof(addr);
 
 bzero(&addr,sizeof(addr));
 while(1)
 {
  char buf[200]  = "";
  char ipbuf[16] = "";
  recvfrom(udpfd, buf, sizeof(buf), 0, (struct sockaddr*)&addr, &addrlen);
  printf("\r\033[31m[%s]:\033[32m%s\n",inet_ntop(AF_INET,&addr.sin_addr,ipbuf,sizeof(ipbuf)),buf);
  write(1,"UdpQQ:",6);
 }
 return NULL;
}

int main(int argc,char *argv[])
{
 char buf[100] = "";
 int  udpfd = 0;
 pthread_t tid;
 struct sockaddr_in addr;
 struct sockaddr_in cliaddr;
 
 //初始化套接字位址
 bzero(&addr,sizeof(addr));
 addr.sin_family = AF_INET;
 addr.sin_port  = htons(8000);
 addr.sin_addr.s_addr = htonl(INADDR_ANY);

 bzero(&cliaddr,sizeof(cliaddr)); 
 cliaddr.sin_family = AF_INET;
 cliaddr.sin_port  = htons(8000);

 //建立套接字
 if( (udpfd = socket(AF_INET,SOCK_DGRAM, 0)) < 0)
 {
  perror("socket error");
  exit(-1);
 }
 
 //綁定連接埠
 if(bind(udpfd, (struct sockaddr*)&addr, sizeof(addr)) < 0)
 {
  perror("bind error");
  close(udpfd); 
  exit(-1);
 }
 
 printf("input: \"sayto 192.168.221.X\" to sendmsg to somebody\n");
 //建立接收執行緒
 pthread_create(&tid, NULL, recv_thread, (void*)udpfd); //建立執行緒
 printf("\033[32m"); //設定字型顏色
 fflush(stdout);
 
 while(1)
 { 
  //主執行緒負責送出訊息
  write(1,"UdpQQ:",6);//1 代表標準輸出
  fgets(buf, sizeof(buf), stdin); //等待輸入
  buf[strlen(buf) - 1] = '\0';    //確保輸入最後一位是 '\0'
  if(strncmp(buf, "sayto", 5) == 0)
  {
   char ipbuf[INET_ADDRSTRLEN] = "";
   inet_pton(AF_INET, buf+6, &cliaddr.sin_addr);//重新為位址賦值
   printf("\rconnect %s successful!\n",inet_ntop(AF_INET,&cliaddr.sin_addr,ipbuf,sizeof(ipbuf)));
   continue;
  }
  else if(strncmp(buf, "exit",4) == 0)
  {
   close(udpfd);
   exit(0);
  }
 
  sendto(udpfd, buf, strlen(buf),0,(struct sockaddr*)&cliaddr, sizeof(cliaddr));
 }
 
 return 0;
}

接著改用 select 完成一模一樣的功能,全程只需要一條執行緒:

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main(int argc,char *argv[])
{
 int udpfd = 0;
 struct sockaddr_in saddr;
 struct sockaddr_in caddr;

 bzero(&saddr,sizeof(saddr));
 saddr.sin_family = AF_INET;
 saddr.sin_port  = htons(8000);
 saddr.sin_addr.s_addr = htonl(INADDR_ANY);
 
 bzero(&caddr,sizeof(caddr));
 caddr.sin_family  = AF_INET;
 caddr.sin_port    = htons(8000);
 
 //建立套接字
 if( (udpfd = socket(AF_INET,SOCK_DGRAM, 0)) < 0)
 {
  perror("socket error");
  exit(-1);
 }
 
 //綁定連接埠
 if(bind(udpfd, (struct sockaddr*)&saddr, sizeof(saddr)) != 0)
 {
  perror("bind error");
  close(udpfd); 
  exit(-1);
 }

 printf("input: \"sayto 192.168.220.X\" to sendmsg to somebody\033[32m\n"); 
 while(1)
 { 
  char buf[100]=""; 
  fd_set rset; //建立描述符集合 
  FD_ZERO(&rset); //集合清 0
  FD_SET(0, &rset);//將標準輸入加入集合
  FD_SET(udpfd, &rset);//將 udpfd 加入集合 
  write(1,"UdpQQ:",6);
 
  if(select(udpfd + 1, &rset, NULL, NULL, NULL) > 0)
  {
   if(FD_ISSET(0, &rset))//檢測 0 是否可讀
   {   
    fgets(buf, sizeof(buf), stdin);
    buf[strlen(buf) - 1] = '\0';
    if(strncmp(buf, "sayto", 5) == 0)
    {
     char ipbuf[16] = "";
     inet_pton(AF_INET, buf+6, &caddr.sin_addr);//重新為位址賦值
     printf("\rsay to %s\n",inet_ntop(AF_INET,&caddr.sin_addr,ipbuf,sizeof(ipbuf)));
     continue;
    }
    else if(strcmp(buf, "exit")==0)
    {
     close(udpfd);
     exit(0);
    }
    sendto(udpfd, buf, strlen(buf),0,(struct sockaddr*)&caddr, sizeof(caddr));
   }
   if(FD_ISSET(udpfd, &rset))//檢測 udpfd 是否可讀
   {
    struct sockaddr_in addr;
    char ipbuf[INET_ADDRSTRLEN] = "";
    socklen_t addrlen = sizeof(addr);
   
    bzero(&addr,sizeof(addr));
   
    recvfrom(udpfd, buf, 100, 0, (struct sockaddr*)&addr, &addrlen);
    printf("\r\033[31m[%s]:\033[32m%s\n",inet_ntop(AF_INET,&addr.sin_addr,ipbuf,sizeof(ipbuf)),buf);
   }
  }
 }
 
 return 0;
}

兩相比較不難發現:多執行緒版本要處理執行緒建立、資料共享與同步等額外成本,而 select 版本靠著一個集合與一次輪詢,就把「讀鍵盤」與「收封包」這兩件事收攏在同一條執行緒裡,結構單純、開銷更低,這正是 I/O 多工的魅力所在。

本文程式碼可至 Linux 公社資源站下載:

------------------------------------------分割線------------------------------------------

免費下載網址 https://linux.linuxidc.com/

帳號與密碼皆為www.linuxidc.com

實際下載目錄為 /2017年資料/2月/13日/Linux網絡編程:IO復用之select詳解/

下載方式參見 https://www.linuxidc.com/Linux/2013-07/87684.htm

------------------------------------------分割線------------------------------------------

Copyright © Linux教程網 All Rights Reserved