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