欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

IO多路復(fù)用之select全面總結(jié)(必看篇)

 更新時(shí)間:2016年12月24日 11:05:09   投稿:jingxian  
下面小編就為大家?guī)?lái)一篇IO多路復(fù)用之select全面總結(jié)(必看篇)。小編覺(jué)得挺不錯(cuò)的。現(xiàn)在就分享給大家。也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧

1、基本概念

IO多路復(fù)用是指內(nèi)核一旦發(fā)現(xiàn)進(jìn)程指定的一個(gè)或者多個(gè)IO條件準(zhǔn)備讀取,它就通知該進(jìn)程。IO多路復(fù)用適用如下場(chǎng)合:

(1)當(dāng)客戶(hù)處理多個(gè)描述字時(shí)(一般是交互式輸入和網(wǎng)絡(luò)套接口),必須使用I/O復(fù)用。

(2)當(dāng)一個(gè)客戶(hù)同時(shí)處理多個(gè)套接口時(shí),而這種情況是可能的,但很少出現(xiàn)。

(3)如果一個(gè)TCP服務(wù)器既要處理監(jiān)聽(tīng)套接口,又要處理已連接套接口,一般也要用到I/O復(fù)用。

(4)如果一個(gè)服務(wù)器即要處理TCP,又要處理UDP,一般要使用I/O復(fù)用。

(5)如果一個(gè)服務(wù)器要處理多個(gè)服務(wù)或多個(gè)協(xié)議,一般要使用I/O復(fù)用。

與多進(jìn)程和多線程技術(shù)相比,I/O多路復(fù)用技術(shù)的最大優(yōu)勢(shì)是系統(tǒng)開(kāi)銷(xiāo)小,系統(tǒng)不必創(chuàng)建進(jìn)程/線程,也不必維護(hù)這些進(jìn)程/線程,從而大大減小了系統(tǒng)的開(kāi)銷(xiāo)。

2、select函數(shù)

該函數(shù)準(zhǔn)許進(jìn)程指示內(nèi)核等待多個(gè)事件中的任何一個(gè)發(fā)送,并只在有一個(gè)或多個(gè)事件發(fā)生或經(jīng)歷一段指定的時(shí)間后才喚醒。函數(shù)原型如下:

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

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

返回值:就緒描述符的數(shù)目,超時(shí)返回0,出錯(cuò)返回-1

函數(shù)參數(shù)介紹如下:

(1)第一個(gè)參數(shù)maxfdp1指定待測(cè)試的描述字個(gè)數(shù),它的值是待測(cè)試的最大描述字加1(因此把該參數(shù)命名為maxfdp1),描述字0、1、2...maxfdp1-1均將被測(cè)試。

因?yàn)槲募枋龇菑?開(kāi)始的。

(2)中間的三個(gè)參數(shù)readset、writeset和exceptset指定我們要讓內(nèi)核測(cè)試讀、寫(xiě)和異常條件的描述字。如果對(duì)某一個(gè)的條件不感興趣,就可以把它設(shè)為空指針。struct fd_set可以理解為一個(gè)集合,這個(gè)集合中存放的是文件描述符,可通過(guò)以下四個(gè)宏進(jìn)行設(shè)置:

void FD_ZERO(fd_set *fdset);           //清空集合

void FD_SET(int fd, fd_set *fdset);   //將一個(gè)給定的文件描述符加入集合之中

void FD_CLR(int fd, fd_set *fdset);   //將一個(gè)給定的文件描述符從集合中刪除

int FD_ISSET(int fd, fd_set *fdset);   // 檢查集合中指定的文件描述符是否可以讀寫(xiě)

(3)timeout告知內(nèi)核等待所指定描述字中的任何一個(gè)就緒可花多少時(shí)間。其timeval結(jié)構(gòu)用于指定這段時(shí)間的秒數(shù)和微秒數(shù)。

     struct timeval{

          long tv_sec;  //seconds

          long tv_usec; //microseconds

    };

這個(gè)參數(shù)有三種可能:

(1)永遠(yuǎn)等待下去:僅在有一個(gè)描述字準(zhǔn)備好I/O時(shí)才返回。為此,把該參數(shù)設(shè)置為空指針NULL。

(2)等待一段固定時(shí)間:在有一個(gè)描述字準(zhǔn)備好I/O時(shí)返回,但是不超過(guò)由該參數(shù)所指向的timeval結(jié)構(gòu)中指定的秒數(shù)和微秒數(shù)。

(3)根本不等待:檢查描述字后立即返回,這稱(chēng)為輪詢(xún)。為此,該參數(shù)必須指向一個(gè)timeval結(jié)構(gòu),而且其中的定時(shí)器值必須為0。

 原理圖:

3、測(cè)試程序

寫(xiě)一個(gè)TCP回射程序,程序的功能是:客戶(hù)端向服務(wù)器發(fā)送信息,服務(wù)器接收并原樣發(fā)送給客戶(hù)端,客戶(hù)端顯示出接收到的信息。

服務(wù)端程序如下:

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

#define IPADDR   "127.0.0.1"
#define PORT    8787
#define MAXLINE   1024
#define LISTENQ   5
#define SIZE    10

typedef struct server_context_st
{
  int cli_cnt;    /*客戶(hù)端個(gè)數(shù)*/
  int clifds[SIZE];  /*客戶(hù)端的個(gè)數(shù)*/
  fd_set allfds;   /*句柄集合*/
  int maxfd;     /*句柄最大值*/
} server_context_st;
static server_context_st *s_srv_ctx = NULL;
/*===========================================================================
 * ==========================================================================*/
static int create_server_proc(const char* ip,int port)
{
  int fd;
  struct sockaddr_in servaddr;
  fd = socket(AF_INET, SOCK_STREAM,0);
  if (fd == -1) {
    fprintf(stderr, "create socket fail,erron:%d,reason:%s\n",
        errno, strerror(errno));
    return -1;
  }

  /*一個(gè)端口釋放后會(huì)等待兩分鐘之后才能再被使用,SO_REUSEADDR是讓端口釋放后立即就可以被再次使用。*/
  int reuse = 1;
  if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) == -1) {
    return -1;
  }

  bzero(&servaddr,sizeof(servaddr));
  servaddr.sin_family = AF_INET;
  inet_pton(AF_INET,ip,&servaddr.sin_addr);
  servaddr.sin_port = htons(port);

  if (bind(fd,(struct sockaddr*)&servaddr,sizeof(servaddr)) == -1) {
    perror("bind error: ");
    return -1;
  }

  listen(fd,LISTENQ);

  return fd;
}

static int accept_client_proc(int srvfd)
{
  struct sockaddr_in cliaddr;
  socklen_t cliaddrlen;
  cliaddrlen = sizeof(cliaddr);
  int clifd = -1;

  printf("accpet clint proc is called.\n");

ACCEPT:
  clifd = accept(srvfd,(struct sockaddr*)&cliaddr,&cliaddrlen);

  if (clifd == -1) {
    if (errno == EINTR) {
      goto ACCEPT;
    } else {
      fprintf(stderr, "accept fail,error:%s\n", strerror(errno));
      return -1;
    }
  }

  fprintf(stdout, "accept a new client: %s:%d\n",
      inet_ntoa(cliaddr.sin_addr),cliaddr.sin_port);

  //將新的連接描述符添加到數(shù)組中
  int i = 0;
  for (i = 0; i < SIZE; i++) {
    if (s_srv_ctx->clifds[i] < 0) {
      s_srv_ctx->clifds[i] = clifd;
      s_srv_ctx->cli_cnt++;
      break;
    }
  }

  if (i == SIZE) {
    fprintf(stderr,"too many clients.\n");
    return -1;
  }
101 }

static int handle_client_msg(int fd, char *buf) 
{
  assert(buf);
  printf("recv buf is :%s\n", buf);
  write(fd, buf, strlen(buf) +1);
  return 0;
}

static void recv_client_msg(fd_set *readfds)
{
  int i = 0, n = 0;
  int clifd;
  char buf[MAXLINE] = {0};
  for (i = 0;i <= s_srv_ctx->cli_cnt;i++) {
    clifd = s_srv_ctx->clifds[i];
    if (clifd < 0) {
      continue;
    }
    /*判斷客戶(hù)端套接字是否有數(shù)據(jù)*/
    if (FD_ISSET(clifd, readfds)) {
      //接收客戶(hù)端發(fā)送的信息
      n = read(clifd, buf, MAXLINE);
      if (n <= 0) {
        /*n==0表示讀取完成,客戶(hù)都關(guān)閉套接字*/
        FD_CLR(clifd, &s_srv_ctx->allfds);
        close(clifd);
        s_srv_ctx->clifds[i] = -1;
        continue;
      }
      handle_client_msg(clifd, buf);
    }
  }
}
static void handle_client_proc(int srvfd)
{
  int clifd = -1;
  int retval = 0;
  fd_set *readfds = &s_srv_ctx->allfds;
  struct timeval tv;
  int i = 0;

  while (1) {
    /*每次調(diào)用select前都要重新設(shè)置文件描述符和時(shí)間,因?yàn)槭录l(fā)生后,文件描述符和時(shí)間都被內(nèi)核修改啦*/
    FD_ZERO(readfds);
    /*添加監(jiān)聽(tīng)套接字*/
    FD_SET(srvfd, readfds);
    s_srv_ctx->maxfd = srvfd;

    tv.tv_sec = 30;
    tv.tv_usec = 0;
    /*添加客戶(hù)端套接字*/
    for (i = 0; i < s_srv_ctx->cli_cnt; i++) {
      clifd = s_srv_ctx->clifds[i];
      /*去除無(wú)效的客戶(hù)端句柄*/
      if (clifd != -1) {
        FD_SET(clifd, readfds);
      }
      s_srv_ctx->maxfd = (clifd > s_srv_ctx->maxfd ? clifd : s_srv_ctx->maxfd);
    }

    /*開(kāi)始輪詢(xún)接收處理服務(wù)端和客戶(hù)端套接字*/
    retval = select(s_srv_ctx->maxfd + 1, readfds, NULL, NULL, &tv);
    if (retval == -1) {
      fprintf(stderr, "select error:%s.\n", strerror(errno));
      return;
    }
    if (retval == 0) {
      fprintf(stdout, "select is timeout.\n");
      continue;
    }
    if (FD_ISSET(srvfd, readfds)) {
      /*監(jiān)聽(tīng)客戶(hù)端請(qǐng)求*/
      accept_client_proc(srvfd);
    } else {
      /*接受處理客戶(hù)端消息*/
      recv_client_msg(readfds);
    }
  }
}

static void server_uninit()
{
  if (s_srv_ctx) {
    free(s_srv_ctx);
    s_srv_ctx = NULL;
  }
}

static int server_init()
{
  s_srv_ctx = (server_context_st *)malloc(sizeof(server_context_st));
  if (s_srv_ctx == NULL) {
    return -1;
  }

  memset(s_srv_ctx, 0, sizeof(server_context_st));

  int i = 0;
  for (;i < SIZE; i++) {
    s_srv_ctx->clifds[i] = -1;
  }

  return 0;
}

int main(int argc,char *argv[])
{
  int srvfd;
  /*初始化服務(wù)端context*/
  if (server_init() < 0) {
    return -1;
  }
  /*創(chuàng)建服務(wù),開(kāi)始監(jiān)聽(tīng)客戶(hù)端請(qǐng)求*/
  srvfd = create_server_proc(IPADDR, PORT);
  if (srvfd < 0) {
    fprintf(stderr, "socket create or bind fail.\n");
    goto err;
  }
  /*開(kāi)始接收并處理客戶(hù)端請(qǐng)求*/
  handle_client_proc(srvfd);
  server_uninit();
  return 0;
err:
  server_uninit();
  return -1;
}

客戶(hù)端程序如下:

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

#define MAXLINE 1024
#define IPADDRESS "127.0.0.1"
#define SERV_PORT 8787

#define max(a,b) (a > b) ? a : b

static void handle_recv_msg(int sockfd, char *buf) 
{
printf("client recv msg is:%s\n", buf);
sleep(5);
write(sockfd, buf, strlen(buf) +1);
}

static void handle_connection(int sockfd)
{
char sendline[MAXLINE],recvline[MAXLINE];
int maxfdp,stdineof;
fd_set readfds;
int n;
struct timeval tv;
int retval = 0;

while (1) {

FD_ZERO(&readfds);
FD_SET(sockfd,&readfds);
maxfdp = sockfd;

tv.tv_sec = 5;
tv.tv_usec = 0;

retval = select(maxfdp+1,&readfds,NULL,NULL,&tv);

if (retval == -1) {
return ;
}

if (retval == 0) {
printf("client timeout.\n");
continue;
}

if (FD_ISSET(sockfd, &readfds)) {
n = read(sockfd,recvline,MAXLINE);
if (n <= 0) {
fprintf(stderr,"client: server is closed.\n");
close(sockfd);
FD_CLR(sockfd,&readfds);
return;
}

handle_recv_msg(sockfd, recvline);
}
}
}

int main(int argc,char *argv[])
{
int sockfd;
struct sockaddr_in servaddr;

sockfd = socket(AF_INET,SOCK_STREAM,0);

bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(SERV_PORT);
inet_pton(AF_INET,IPADDRESS,&servaddr.sin_addr);

int retval = 0;
retval = connect(sockfd,(struct sockaddr*)&servaddr,sizeof(servaddr));
if (retval < 0) {
fprintf(stderr, "connect fail,error:%s\n", strerror(errno));
return -1;
}

printf("client send to server .\n");
write(sockfd, "hello server", 32);

handle_connection(sockfd);

return 0;
}

4、程序結(jié)果

啟動(dòng)服務(wù)程序,執(zhí)行三個(gè)個(gè)客戶(hù)程序進(jìn)行測(cè)試,結(jié)果如下圖所示:

以上就是小編為大家?guī)?lái)的IO多路復(fù)用之select全面總結(jié)(必看篇)全部?jī)?nèi)容了,希望大家多多支持腳本之家~

相關(guān)文章

  • Linux:FTP工具及SSH遠(yuǎn)程連接工具的使用方式

    Linux:FTP工具及SSH遠(yuǎn)程連接工具的使用方式

    這篇文章主要介紹了Linux:FTP工具及SSH遠(yuǎn)程連接工具的使用方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-02-02
  • Linux中的信號(hào)(注冊(cè),注銷(xiāo),處理,阻塞)

    Linux中的信號(hào)(注冊(cè),注銷(xiāo),處理,阻塞)

    這篇文章主要介紹了Linux中的信號(hào)(注冊(cè),注銷(xiāo),處理,阻塞),具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-02-02
  • Linux如何查看架構(gòu)和系統(tǒng)問(wèn)題

    Linux如何查看架構(gòu)和系統(tǒng)問(wèn)題

    在Linux系統(tǒng)上,可以使用`uname?-m`查看系統(tǒng)架構(gòu),使用`uname`查看內(nèi)核和操作系統(tǒng)信息,使用`/etc/os-release`和`lsb_release`查看系統(tǒng)詳細(xì)信息,使用`lscpu`、`lsblk`和`free?-h`查看硬件信息
    2025-03-03
  • Linux系統(tǒng)用戶(hù)如何添加到用戶(hù)組

    Linux系統(tǒng)用戶(hù)如何添加到用戶(hù)組

    這篇文章主要介紹了Linux系統(tǒng)用戶(hù)如何添加到用戶(hù)組問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-07-07
  • Linux echo文本處理命令的使用及示例

    Linux echo文本處理命令的使用及示例

    這篇文章主要介紹了Linux echo文本處理命令的使用及示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-03-03
  • CentOS 6.4 中安裝php5.2.17 的方法

    CentOS 6.4 中安裝php5.2.17 的方法

    最近給一個(gè)公司部署服務(wù)器的時(shí)候發(fā)現(xiàn)他們提供的服務(wù)器是redhat 6.4系統(tǒng)的,又沒(méi)有注冊(cè),只好修改yum源。
    2016-06-06
  • 詳解Centos中mount命令掛載windows7共享目錄

    詳解Centos中mount命令掛載windows7共享目錄

    本篇文章主要介紹了Centos中mount命令掛載windows7共享目錄,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。
    2017-03-03
  • Linux如何設(shè)置java.library.path

    Linux如何設(shè)置java.library.path

    這篇文章主要介紹了Linux如何設(shè)置java.library.path問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-12-12
  • Linux 掛載磁盤(pán)詳解及實(shí)操步驟

    Linux 掛載磁盤(pán)詳解及實(shí)操步驟

    Linux中掛載磁盤(pán)是一項(xiàng)重要的操作,可以用于擴(kuò)展存儲(chǔ)空間,管理數(shù)據(jù)文件,備份和存儲(chǔ)重要文件等,本文將詳細(xì)介紹Linux系統(tǒng)中掛載磁盤(pán)的相關(guān)概念、步驟和實(shí)際操作指南
    2023-06-06
  • Linux下如何查看版本信息的方法步驟

    Linux下如何查看版本信息的方法步驟

    這篇文章主要介紹了Linux下如何查看版本信息的方法步驟,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-12-12

最新評(píng)論