Poll function of--I/O multiplexing for Linux network programming

Source: Internet
Author: User
Tags readable socket error htons

First, review the previous Select
Select Advantages:
currently supported on almost all platforms, and its good cross-platform support is one of its advantages
Select Cons:
1. Each call to select () requires that the FD collection be copied from the user state to the kernel state, which is very expensive when FD is very large, and each call to select () requires the kernel to traverse all the FD that is passed in, which is also very expensive in FD.

2. There is a maximum limit on the number of file descriptors that a single process can monitor, typically 1024 on Linux, which can be improved by modifying the macro definition or even recompiling the kernel, but this also results in reduced efficiency

Ii. Overview of poll functions
Like the essence of the Select () and poll () system calls, the mechanism of poll () is similar to select (), with no significant difference in nature with select (), and the management of multiple descriptors is also polling, which is handled according to the state of the descriptor, but poll () There is no limit to the maximum number of file descriptors (but performance is also degraded if the number is too large). The disadvantage of poll () and select () is that an array containing a large number of file descriptors is copied in between the user state and the kernel's address space, regardless of whether the file descriptor is ready, and its overhead increases linearly as the number of file descriptors increases. The poll () function describes the header file: [CSharp]View Plain Copy
    1. #include <poll.h>
function Body: [CSharp]View Plain Copy
    1. int poll (struct POLLFD *fds, nfds_t nfds, int timeout);
Features:
Monitor and wait for property changes for multiple file descriptors

Parameters:

FDS: A pointer to the NO. 0 element of a struct array, each of which is a struct POLLFD structure that specifies the condition for testing a given FD

 

[CSHARP]  view plain  copy  
  1. STRUCT&NBSP;POLLFD{&NBSP;&NBSP;
  2.     int  fd;         //file descriptor   
  3.     short events;    //waiting event   
  4.     short revents;  //the events actually occurred   
  5. };&NBSP;&NBSP;

FD: Each pollfd struct specifies a monitored file descriptor that can pass multiple structures, indicating that poll () monitors multiple file descriptors.

Events: Specifies the event (input, output, error) that monitors FD, with multiple values for each event, as follows:



The Revents:revents field is the action result event for the file descriptor, and the kernel sets the field when the call returns. Any events requested in the events domain may be returned in the revents domain.

Note: The events field of each struct is set by the user, telling the kernel what we are interested in, and the revents domain is the kernel set at the time of the return to indicate what happened to the descriptor.

Nfds: Used to specify the number of elements in the first parameter array

Timeout: Specifies the number of milliseconds to wait for poll () to return, regardless of whether I/O is ready.

return value:

On success, poll () returns the number of file descriptors that are not 0 in the Revents field in the struct, or poll () returns 0 if no events occur before the timeout;


On Failure, poll () returns 1 and sets errno to one of the following values:

EBADF: Invalid file descriptor specified in one or more structs.

The address that the Efault:fds pointer points to exceeds the address space of the process.

EINTR: The requested event generates a signal before the call can be re-initiated.

The Einval:nfds parameter exceeds the Plimit_nofile value.

Enomem: There is not enough memory available to complete the request.

Iii. Examples of poll example
Implement UDP to send and receive code with poll: [CSharp]View Plain Copy
  1. #include <string.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <unistd.h>
  5. #include <sys/select.h>
  6. #include <sys/time.h>
  7. #include <sys/socket.h>
  8. #include <netinet/in.h>
  9. #include <arpa/inet.h>
  10. #include <poll.h>
  11. int main (int argc,char *argv[])
  12. {
  13. int udpfd = 0;
  14. int ret = 0;
  15. struct POLLFD fds[2]; //Monitor file Description structure array: 2 x
  16. struct sockaddr_in saddr;
  17. struct sockaddr_in caddr;
  18. Bzero (&saddr,sizeof (SADDR));
  19. saddr.sin_family = af_inet;
  20. Saddr.sin_port = htons (8000);
  21. SADDR.SIN_ADDR.S_ADDR = htonl (Inaddr_any);
  22. Bzero (&caddr,sizeof (CADDR));
  23. caddr.sin_family = af_inet;
  24. Caddr.sin_port = htons (8000);
  25. //Create sockets
  26. if ((UDPFD = socket (af_inet,sock_dgram, 0)) < 0)
  27. {
  28. Perror ("socket error");
  29. Exit (-1);
  30. }
  31. //Socket Port binding
  32. if (Bind (UDPFD, (struct sockaddr*) &saddr, sizeof (SADDR))! = 0)
  33. {
  34. Perror ("bind error");
  35. Close (UDPFD);
  36. Exit (-1);
  37. }
  38. printf ("input: \" Sayto 192.168.220.x\ "to Sendmsg to somebody\033[32m\n");
  39. FDS[0].FD = 0; //Standard input descriptor
  40. FDS[1].FD = UDPFD; //UDP Descriptor
  41. Fds[0].events = Pollin; //Normal or priority with data- readable
  42. Fds[1].events = Pollin; //Normal or priority with data- readable
  43. While (1)
  44. {
  45. //monitor and wait for multiple files (standard input, UDP socket) Descriptor property changes (readable)
  46. //No attribute changes, this function blocks until a change is performed, no timeout is set here
  47. RET = Poll (FDS, 2,-1);
  48. Write (1,"UDPQQ:", 6);
  49. if (ret = =-1) { //error
  50. Perror ("poll ()");
  51. }
  52. Else if (Ret > 0) { //prepared file descriptor
  53. char buf[100] = {0};
  54. if ((fds[0].revents & pollin) = = Pollin) { //Standard input
  55. Fgets (buf, sizeof (BUF), stdin);
  56. Buf[strlen (BUF)-1] = ' + ';
  57. if (strncmp (buf, "Sayto", 5) = = 0)
  58. {
  59. char ipbuf[16] = "";
  60. Inet_pton (Af_inet, buf+6, &caddr.sin_addr);  //Assign a value to the addr socket address.
  61. printf ("\rsay to%s\n", Inet_ntop (Af_inet,&caddr.sin_addr,ipbuf,sizeof (IPBUF)));
  62. continue;
  63. }
  64. Else if (strcmp (buf, "exit") ==0)
  65. {
  66. Close (UDPFD);
  67. Exit (0);
  68. }
  69. SendTo (UDPFD, buf, strlen (BUF), 0, (struct sockaddr*) &caddr, sizeof (CADDR));
  70. }
  71. Else if ((fds[1].revents & pollin) = = Pollin) { //udp socket
  72. struct sockaddr_in addr;
  73. char Ipbuf[inet_addrstrlen] = "";
  74. socklen_t Addrlen = sizeof (addr);
  75. Bzero (&addr,sizeof (addr));
  76. Recvfrom (UDPFD, buf, 0, (struct sockaddr*) &addr, &addrlen);
  77. printf ("\r\033[31m[%s]:\033[32m%s\n", Inet_ntop (Af_inet,&addr.sin_addr,ipbuf,sizeof (IPBUF)), buf);
  78. }
  79. }
  80. Else if (0 = = ret) { //timeout
  81. printf ("Time out\n");
  82. }
  83. }
  84. return 0;
  85. }


Operation Result:

Poll function of--I/O multiplexing for Linux network programming

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.