This change is the result of a code audit. The changes are not drastic, but should...
[vsys.git] / tests / vsys_conctest.c
1 #include <stdio.h>
2 #include <sys/select.h>
3 #include <sys/time.h>
4 #include <sys/types.h>
5 #include <sys/stat.h>
6 #include <fcntl.h>
7 #include <unistd.h>
8 #include <errno.h>
9
10 int main()
11 {
12   FILE *fp = NULL, *fp_in = NULL;
13   FILE *out_fp = NULL, *diff_fp = NULL;
14   const char* topcmd = "fe/test.out";
15   const char* top_in_file = "fe/test.in";
16   char buf[4096];
17   int fd_in = -1, fd_out;
18   int res;
19   int flag;
20   int count = 1;
21   struct timeval tv={.tv_sec=5,.tv_usec=0};
22
23   while (count < 100000) {
24     fd_set readSet;
25     int res;
26     int nlines=0;
27
28     //usleep(200);
29     printf("(%d)", count);fflush(stdout);
30
31     if ((fd_out = open(topcmd, O_RDONLY | O_NONBLOCK)) < 0) {
32       fprintf(stderr, "error executing top\n");
33       exit(-1);
34     }
35
36     printf("Opening...\n");
37     if ((fd_in = open(top_in_file, O_WRONLY)) < 0) {
38       fprintf(stderr, "error opening %s\n", top_in_file);
39       exit(-1);
40     }
41     printf("Open.\n");
42
43     if ((flag = fcntl(fd_out, F_GETFL)) == -1) {
44       printf("fcntl get failed\n");
45       exit(-1);
46     }
47
48     while (1) {
49             FD_ZERO(&readSet);
50             FD_SET(fd_out, &readSet);
51
52     printf("Selecting...\n");
53                 sleep(1);
54             res = select(fd_out + 1, &readSet, NULL, NULL, NULL);
55     printf("Selected...\n");
56             if (res < 0) {
57                     if (errno == EINTR || errno == EAGAIN) {
58                             printf(".");
59                             continue;
60                     }
61                     fprintf(stderr,"select failed errno=%d errstr=%s\n", errno, strerror(errno));
62                     exit(-1);
63             }
64             break; /* we're done */
65     }
66
67     if (fcntl(fd_out, F_SETFL, flag & ~O_NONBLOCK) == -1) {
68       printf("fcntl set failed\n");
69       exit(-1);
70     }
71
72     if ((flag = fcntl(fd_out, F_GETFL)) == -1) {
73       printf("fcntl get failed\n");
74       exit(-1);
75     }
76
77     if (flag & O_NONBLOCK == 0) {
78       printf("fd_out still nonblocking\n");
79       exit(-1);
80     }
81
82     if ((fp = fdopen(fd_out, "r")) == NULL) {
83       printf("fdopen failed\n");
84       exit(-1);
85     }
86
87     while (fgets(buf, sizeof(buf), fp) != NULL) {
88             nlines++;
89     }
90
91     if (nlines<5) {
92             printf("Test returned different results - run again to verify\n");
93             exit(-1);
94     }
95
96     fclose(fp);
97     close(fd_in);
98     close(fd_out);
99     count++;
100   }
101   printf("test successful.\n");
102   exit(0);
103
104 }