Linux/unix Network Programming Select

Source: Internet
Author: User
Tags readable

Transfer from http://www.cnblogs.com/zhuwbox/p/4221934.html

The sixth chapter of the Select Knowledge Point UNP under Linux has been described very clearly, and here we simply say the role of select and give the client instance of select. We know that select is one of the simplest supports for IO multiplexing, and poll and Epoll are the upgraded versions of select. In the UNIX Network programming Fifth Chapter reading notes we encounter a problem where the server disconnects when the client blocks at fgets () waiting for customer input. But the client can not know in time, only when the customer input completed and sent to the server to know that the connection has been disconnected, but this may have been a long time. What if we want to know in time what the server is disconnecting?

We know that whether fgets () waits for customer input or read () reads data from the socket interface, it is an IO operation. We cannot block one of the IO operations, so that other IO operations will not work, even if there is data on other IO operations, we will not be able to read them in time. The principle of select is this: we put together the file descriptors that these IO operations want to manipulate (such as an array), and then block on the Select () function, why block here? In fact, the select does not stop traversing this array, to see if the file descriptor is readable/writable, once readable/writable, select returns, stop blocking. Then we describe the readable/writable file as a corresponding operation. The following is the prototype of the SELECT function:

  int Select (Nfds, Readfds, Writefds, Exceptfds, timeout)

Nfds is the maximum file descriptor to be traversed by the specified select () + 1,readfds is the array of file descriptions, which is concerned with the read event of the file descriptor in the array, and Wretefds is also an array of file descriptors. This array is concerned with the write event of the file descriptor in the array, Exceptfds is also an array of file descriptors, which is concerned with the error event of the file descriptor in this array. Timeout is the time when select is blocked. If set to a null pointer, it will be blocked forever until a description have event occurs (ready). Otherwise, it will be returned after blocking the time specified by timeout, regardless of whether there is an event in the file descriptor of interest. Select returns the number of file descriptors that have occurred for the event, failure returns 1, and the timeout returns 0!

  The following is the Select app in the client instance code:

#include <sys/socket.h>#include<netinet/inch.h>#include<stdio.h>#include<error.h>#include<unistd.h>#include<string.h>#include<stdlib.h>#include<sys/wait.h>#include<signal.h>#include<sys/Select.h>#include<sys/time.h>#defineMAXLINE 15#defineSA struct SOCKADDRvoidSTR_CLI (FILE *FP,intsockfd) {    CharSendline[maxline], recvline[maxline],buf[maxline]; intwritenbytes; Fd_set RSet;//file descriptors that care about read events are combined    intMAXFDPL, stdineof; intCounts =0, N; //set all bits clear 0Fd_zero (&RSet);  for(;;) {        //opens the corresponding position switch in the set (FP) descriptor, indicating concern for this descriptorFd_set (Fileno (FP), &RSet); //opens the corresponding position switch of the SOCKFD descriptor in the collection, indicating concern for this descriptorFd_set (SOCKFD, &RSet); //set to Maximum descriptor + 1MAXFDPL = (sockfd > Fileno (FP)? Sockfd:fileno (FP)) +1; //will clog up here .        if((counts =Select(MAXFDPL, &rset, NULL, NULL, NULL)) >0)        {            //whether a readable event occurs on the SOCKFD descriptor (that is, the server sends the data over)            if(Fd_isset (SOCKFD, &RSet)) {                if((n = Read (SOCKFD, buf, MAXLINE)) = =0)                {                    if(stdineof =1)                        return; Else{printf ("Str_cli:server terminated prematurely!\n"); Exit (0); }                            }                if((n = Write (Fileno (stdout), BUF, n))! =N) {printf ("str_cli:write () error!\n"); Exit (0); }            }            //whether a readable event occurs on the FP descriptor (that is, the user entered the data)            if(Fd_isset (Fileno (FP), &RSet)) {                                if((n = Read (Fileno (FP), buf, MAXLINE)) = =0) {stdineof=1;                    Shutdown (SOCKFD, SHUT_WR); FD_CLR (Fileno (FP),&RSet); Continue;            } write (SOCKFD, buf, N); }            }    }}intMainintargcChar**argv) {    intSOCKFD; structsockaddr_in servaddr; if(ARGC! =2) {printf ("useage:tcpcli <IPaddress>"); Exit (0); }    if(SOCKFD = socket (af_inet, Sock_stream,0)) <0) {printf ("socket () error!"); Exit (0); } bzero (&AMP;SERVADDR,sizeof(SERVADDR)); Servaddr.sin_family=af_inet; Servaddr.sin_port= Htons (9806); if(Inet_pton (Af_inet, argv[1], &AMP;SERVADDR.SIN_ADDR) <0) {printf ("Inet_pton () error!"); Exit (0); }    if(Connect (SOCKFD, (SA *) &servaddr,sizeof(SERVADDR)) <0) {printf ("Inet_pton () error!"); Exit (0);    } str_cli (stdin, SOCKFD); Exit (0);}

Linux/unix Network Programming Select

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.