Linux之select系统调用_1,select系统调用_1


SYNOPSIS
       /* According to POSIX.1-2001 */
       #include <sys/select.h>

       /* According to earlier standards */
       #include <sys/time.h>
       #include <sys/types.h>
       #include <unistd.h>

       int select(int nfds, fd_set *readfds, fd_set *writefds,
                  fd_set *exceptfds, struct timeval *timeout);

       void FD_CLR(int fd, fd_set *set);
       int  FD_ISSET(int fd, fd_set *set);
       void FD_SET(int fd, fd_set *set);
       void FD_ZERO(fd_set *set);
DESCRIPTION
       select() allow  a  program  to  monitor  multiple  file
       descriptors,  waiting  until one or more of the file descriptors become
       "ready" for some class of I/O operation (e.g., input possible).  A file
       descriptor  is considered ready if it is possible to perform the corre-
       sponding I/O operation (e.g., read(2)) without blocking.

select函数对数据结构fd_set进行操作,fd_set是一个bitmap,该集合由打开的文件描述符构成。

注意,对于管道而言,select是通过检查管道是否阻塞,来进行监听的。只要所监听的管道非阻塞,select就能立马获知,并将其在fd_set中的相应为置1。管道非阻塞只有两种情况,一种是客户端向管道写东西,另一种是客户端将管道关闭(读端)。当然,对于非阻塞的情况,select能监听到,但它并不会知道非阻塞是因为客户端关闭管道还是客户端向管道写消息。这需要我们自己来判断。通常是通过read系统调用的返回值来判断。read返回0,说明是客户端关闭了管道,read返回正值,说明是客户端向管道写东西了。

也许你会产生这样的疑问,如果有n个客户端,那么我们不是也可以fork出n-1个子进程,共n个进程,用于接收客户端消息吗?实际上这是不可行的,因为我们一个程序最多只能打开1024个进程。因此,此处使用select是很合理的。

代码

实现多个客户端向服务端发送消息,服务端将消息打印在标准输出上。如果有3个客户端,就事先建立3个管道,每个客户端分别使用一个管道向服务器发送消息。而在服务器端使用select系统调用,只要监测到某一管道有消息写入,服务器就将其read,并显示在标准输出上。实现如下:

server.c

/*************************************************************************
  > File Name: server.c
  > Author: KrisChou
  > Mail:zhoujx0219@163.com 
  > Created Time: Sat 23 Aug 2014 02:37:58 PM CST
 ************************************************************************/

#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/select.h>
#include <sys/time.h>

int main(int argc, char* argv[]) 
{
    /* 打开管道 */
    int fd1, fd2, fd3 ;
    fd1= open(argv[1], O_RDONLY);
    fd2= open(argv[2], O_RDONLY);
    fd3= open(argv[3], O_RDONLY);
    
    printf("server: %d \n", getpid());
    
    /* 设置select需要监听的集合fd_set */
    fd_set readset ,bak_set ;
    FD_ZERO(&bak_set);
    FD_SET(fd1, &bak_set);
    FD_SET(fd2, &bak_set);
    FD_SET(fd3, &bak_set);
    /* 设置select轮巡时间 */
    struct timeval  tm ;
    tm.tv_sec = 10 ;
    tm.tv_usec = 0 ;
    /* 可以在程序开始,使得服务器端同时读到3个消息,此处可有可无 */
    sleep(10);
    
    /* select是通过检查管道是否阻塞,来进行监听的。如果均为阻塞,select在轮巡时间内返回0。
     * 如果有管道不阻塞,则select返回不阻塞的管道个数。
     * 注意:当某个客户端向管道发送数据,或者关闭管道,均属于非阻塞状况。
     * 我们可以根据read的返回值来区分这两种情况                                           */
    int nret ; /* select返回值 */
    char buf[1024];
    while(1){
        /* 每次select后都会改变select所监听集合的值,因此需要在每次select的开始重新设置监听集合。
         * 如果不进行设置,那么上次select后监听集合置1的描述符仍然为1。
         * 注意:在Linux系统下,时间也需要重新设置。                                            */
        readset = bak_set ;
        tm.tv_sec = 10 ;
        tm.tv_usec = 0 ;
        nret = select(6 , &readset, NULL, NULL, &tm );
        if(nret > 0)
        {
            printf("%d active ! \n", nret);
            if(FD_ISSET(fd1, &readset))       /* select返回值大于0时,必然有管道不阻塞了,此时需要查看是哪个管道*/
            {
                memset(buf, 0 , 1024);
                if(0 == read(fd1, buf, 1024))
                {
                    FD_CLR(fd1, &bak_set);    /* 如果一个用户其写端已经关闭,那么将其描述符从监听集合中去除 */
                }else 
                {
                    write(1, buf, strlen(buf));
                }
            }
            if(FD_ISSET(fd2, &readset))
            {
                memset(buf, 0 , 1024);
                if(0 == read(fd2, buf, 1024) )
                {
                    FD_CLR(fd2, &bak_set);
                }else
                {
                write(1, buf, strlen(buf));
                }
            }
            if(FD_ISSET(fd3, &readset))
            {
                memset(buf, 0 , 1024);
                if(read(fd3, buf, 1024) == 0)
                {
                    FD_CLR(fd3, &bak_set);
                }else
                {
                    write(1, buf, strlen(buf));
                }
            }


        }else if(nret == 0) 
        {
            printf("time out ! \n");
        }
    }


}

client.c

/*************************************************************************
    > File Name: client.c
    > Author: KrisChou
    > Mail:zhoujx0219@163.com 
    > Created Time: Sat 23 Aug 2014 02:30:54 PM CST
 ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>

int main(int argc, char *argv[])
{
    /* 开启管道 */
    printf("%d start ! \n", getpid());
    int fd_sent;
    fd_sent = open(argv[1],O_WRONLY);
    if(fd_sent == -1)
    {
        perror("open");
        exit(1);
    }
    printf("connect success! \n");

    
    /* 客户端向管道发送消息,按ctrl+D退出循环 */
    
    char line[1024]; /* 从标准输入获得要发送的消息 */
    char msg[1024];  /* 给消息头加一个pid,表示身份 */
    
    while(memset(line,0,1024), fgets(line,1024,stdin) != NULL)
    {
        memset(msg,0,1024);
        sprintf(msg, "%d : %s \n", getpid(), line);
        write(fd_sent, msg, strlen(msg));
    }

    close(fd_sent);
    return 0;
}

执行程序:

mkfifo 1.fifo 2.fifo 3.fifo;
./server.exe 1.fifo 2.fifo 3.fifo
./client 1.fifo
./client 2.fifo
./client 3.fifo

注意1

如果将以下代码去除:

if(0 == read(fd1, buf, 1024))
{
    FD_CLR(fd1, &bak_set);     /* 如果一个用户其写端已经关闭,那么将其描述符从监听集合中去除 */
}

fd2与fd3的也去除,则程序运行,会陷入死循环。原因如下:我们假设客户端关闭了管道1.fifo,那么select就会监听到1.fifo非阻塞,会执行while循环中的if语句,检测到是fd1非阻塞(原因是客户端在写端关闭管道了),那么会执行write(1, buf, strlen(buf)); 因为buf为空,什么也不输出。此时,由于while(1)死循环,select接着监听,由于没有将fd1从监听集合中去除,select立马要监听到其非阻塞…如此循环往复,陷入死循环。当有一个客户端关闭写端,退出后,程序输出结果为:

1 active!
1 active!
1 active!
...

注意2

如果不强制退出,服务端程序永远不会退出去。客户端可以关闭管道退出。也可以在关闭后继续开启管道,与服务器相连。


对于select系统调用的一道题

/*以下程序已经在ubutun LINUX G++上调试成功,采用链表+SELECT()方式,单线程单进程实现了I/O复用技术,而且比原系统写得更为简练一些*/
#include <arpa/inet.h>
#include <errno.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/io.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/times.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#define szBUF 1024

int do_listen(const int port, const int bTcp)
{
int s = 0, r = 0, o = 1;
struct sockaddr_in h;
memset(&h, 0, sizeof(h));
h.sin_family = AF_INET; h.sin_port = htons(port);
h.sin_addr.s_addr = INADDR_ANY;
s = socket(AF_INET, bTcp?SOCK_STREAM:SOCK_DGRAM, 0);
if (s < 1) { perror("socket(listen)"); return 0;}
r = setsockopt(s, SOL_SOCKET,SO_REUSEADDR, (char *)&o, sizeof(int));
if (r == -1) { perror("setsockopt(listen)"); return 0;}
r = bind(s, (struct sockaddr *)&h, sizeof(h));
if (r == -1) { perror("bind(listen)"); return 0;}
if (bTcp) {
r = listen(s, SOMAXCONN);
if (r == -1) { perror("listen()"); return 0;}
}/*end if*/
return s;
}/*end do_listen*/

typedef struct CLIENTS {
int s;
struct CLIENTS * next;
} CL;
CL * locate(CL * head, int sock)
{ CL * h = head; while(h) { if(h->s == sock) return h; h = h->next; } return 0; }

void append(CL ** head, ......余下全文>>
 

linux中对于select的使用问题

select() 函数会修改变量tv的值,你每次调用select()函数前需要再次设置tv。
或者你用pselect()
 

相关内容