1 #include <stdio.h>
2 #include <string.h>
3 #include <stdlib.h>
4 #include <unistd.h>
5 #include <fcntl.h>
6 #include <sys/select.h>
7 #include "tpl.h"
8 
9 #define DEBUG 0
10 
11 extern tpl_hook_t tpl_hook;
12 int num_tpls = 0, sum_tpls = 0;
13 
tpl_cb(void * tpl,size_t tpllen,void * data)14 int tpl_cb(void *tpl, size_t tpllen, void*data) {
15     int i;
16     tpl_node *tn;
17 
18     tpl_hook.oops = printf;
19 
20     if (DEBUG) printf("obtained tpl of length %d\n", (int)tpllen);
21     tn = tpl_map("A(i)", &i);
22     tpl_load(tn, TPL_MEM, tpl, tpllen);
23     num_tpls++;
24     while (tpl_unpack(tn,1) > 0) sum_tpls += i;
25     tpl_free(tn);
26     /* this next line is a hack to test the callback's ability
27      * to abort further tpl processing by returning < 0 */
28     if (num_tpls == 1) return -1;
29     return 0;
30 
31 }
32 
main()33 int main() {
34     FILE *f1,*f2;
35     int fdflags,fd,fd1,fd2;
36     int selrc, maxfd;
37     tpl_gather_t *gs1=NULL,*gs2=NULL,**gs;
38     struct timeval tv;
39     fd_set rset;
40 
41 
42     f1 = popen("cat test26_0.tpl;sleep 1; cat test26_1.tpl", "r");
43     fd1 = fileno(f1);
44     fdflags = fcntl(fd1, F_GETFL, 0);
45     fcntl( fd1, F_SETFL, fdflags | O_NONBLOCK);
46 
47     f2 = popen("cat test26_2.tpl;sleep 1; cat test26_3.tpl", "r");
48     fd2 = fileno(f2);
49     fdflags = fcntl(fd2, F_GETFL, 0);
50     fcntl( fd2, F_SETFL, fdflags | O_NONBLOCK);
51 
52     while (1) {
53         FD_ZERO( &rset );
54         if (fd1 >= 0) FD_SET( fd1, &rset );
55         if (fd2 >= 0) FD_SET( fd2, &rset );
56 
57         if (fd1 == -1 && fd2 == -1) {
58             printf("%d tpls gathered.\n",num_tpls);
59             printf("%d is their sum.\n",sum_tpls);
60             return(0);
61         }
62 
63         maxfd=0;
64         if (fd1>maxfd) maxfd = fd1;
65         if (fd2>maxfd) maxfd = fd2;
66 
67         tv.tv_sec = 5;
68         tv.tv_usec = 0;
69 
70         selrc = select(maxfd+1, &rset, NULL, NULL, &tv );
71         if (selrc == -1) {
72            perror("select()");
73         } else if (selrc) {
74             for(fd=0;fd<maxfd+1;fd++) {
75                 if ( FD_ISSET(fd, &rset) ) {
76                     if (DEBUG) printf("fd %d readable\n", fd);
77                     gs = (fd1 == fd) ? &gs1 : &gs2;
78                     if (tpl_gather(TPL_GATHER_NONBLOCKING,fd,gs,tpl_cb,NULL) <= 0) {
79                         if (fd1 == fd) {pclose(f1); fd1 = -1; }
80                         if (fd2 == fd) {pclose(f2); fd2 = -1; }
81                     } else {
82                         if (DEBUG) printf("tpl_gather >0\n");
83                     }
84                 }
85             }
86         } else {
87             if (DEBUG) printf("timeout\n");
88         }
89     }
90     return(0);
91 }
92