select function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include <errno.h>

#include <stdio.h>

#include <string.h>

#include <sys/time.h>

#include "restart.h"



int copy2files(int fromfd1, int tofd1, int fromfd2, int tofd2) {

   int bytesread;

   int maxfd;

   int num;

   fd_set readset;

   int totalbytes = 0;



   if ((fromfd1 < 0) || (fromfd1 >= FD_SETSIZE) ||

       (tofd1 < 0) || (tofd1 >= FD_SETSIZE) ||

       (fromfd2 < 0) || (fromfd2 >= FD_SETSIZE) ||

       (tofd2 < 0) || (tofd2 >= FD_SETSIZE))

      return 0;

   maxfd = fromfd1;                     /* find the biggest fd for select */

   if (fromfd2 > maxfd)

      maxfd = fromfd2;



   for ( ; ; ) {

      FD_ZERO(&readset);

      FD_SET(fromfd1, &readset);

      FD_SET(fromfd2, &readset);

      if (((num = select(maxfd+1, &readset, NULL, NULL, NULL)) == -1) &&

         (errno == EINTR))

         continue;

      if (num == -1)

         return totalbytes;

      if (FD_ISSET(fromfd1, &readset)) {

         bytesread = readwrite(fromfd1, tofd1);

         if (bytesread <= 0)

            break;

         totalbytes += bytesread;

      }

      if (FD_ISSET(fromfd2, &readset)) {

         bytesread = readwrite(fromfd2, tofd2);

         if (bytesread <= 0)

            break;

         totalbytes += bytesread;

      }

   }

   return totalbytes;

}
whats the purpose this infinite loop here ?
select allows the function do two file copies concurrently on a single thread by multiplexing the file descriptor processing.
The select() on line 53 blocks on the file descriptors (FDs) set in lines 49 and 51. When the select() statement exits, lines 63 and 75 check which file descriptor (if any) has been active. Looks like it reads and then writes back to same file descriptor. It keeps a count of the bytes. The loop is exited if there is an error condition returned by readwrite().
Topic archived. No new replies allowed.