Merge branch 'master' of ssh://gapil.gnulinux.it/srv/git/gapil
[gapil.git] / listati / poll_echod.c
1 ...
2     poll_set = (struct pollfd *) malloc(n * sizeof(struct pollfd));
3     max_fd = list_fd;                 /* maximum now is listening socket */
4     for (i=0; i<n; i++) {             /* initialize poll set */
5         poll_set[i].fd = -1;
6         poll_set[i].events = POLLRDNORM;
7     }
8     poll_set[max_fd].fd = list_fd;    
9     while (1) {   /* main loop, wait for connection and data inside a poll */
10         while ( ((n=poll(poll_set, max_fd + 1, -1)) < 0) && (errno == EINTR));
11         if (n < 0) {                          /* on real error exit */
12             PrintErr("poll error");
13             exit(1);
14         }
15         if (poll_set[list_fd].revents & POLLRDNORM) {  /* if new connection */
16             n--;                              /* decrement active */
17             len = sizeof(c_addr);             /* and call accept */
18             if ((fd = accept(list_fd, (struct sockaddr *)&c_addr, &len)) < 0) {
19                 PrintErr("accept error");
20                 exit(1);
21             }
22             poll_set[fd].fd = fd;             /* set new connection socket */
23             if (max_fd < fd) max_fd = fd;     /* if needed set new maximum */
24         }
25         i = list_fd;                  /* first socket to look */
26         while (n != 0) {              /* loop until active */
27             i++;                      /* start after listening socket */
28             if (poll_set[i].fd == -1) continue;   /* closed, go next */
29             if (poll_set[i].revents & (POLLRDNORM|POLLERR)) {
30                 n--;                         /* decrease active */
31                 nread = read(i, buffer, MAXLINE);     /* read operations */
32                 if (nread < 0) {
33                     PrintErr("Errore in lettura");
34                     exit(1);
35                 }
36                 if (nread == 0) {            /* if closed connection */
37                     close(i);                /* close file */
38                     poll_set[i].fd = -1;          /* mark as closed in table */
39                     if (max_fd == i) {       /* if was the maximum */
40                         while (poll_set[--i].fd == -1);    /* loop down */
41                         max_fd = i;          /* set new maximum */
42                         break;               /* and go back to select */
43                     }
44                     continue;                /* continue loop on open */
45                 }
46                 nwrite = FullWrite(i, buffer, nread); /* write data */
47                 if (nwrite) {
48                     PrintErr("Errore in scrittura");
49                     exit(1);
50                 }
51             }
52         }
53     }
54 ...