ctdb-tests: Fix signed/unsigned comparisons by casting
[samba.git] / ctdb / tests / src / line_test.c
1 /*
2    Test code for line based I/O over fds
3
4    Copyright (C) Amitay Isaacs  2018
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include "replace.h"
21 #include "system/filesys.h"
22
23 #include <talloc.h>
24 #include <assert.h>
25
26 #include "common/line.c"
27
28 static int line_print(char *line, void *private_data)
29 {
30         printf("%s\n", line);
31         fflush(stdout);
32
33         return 0;
34 }
35
36 int main(int argc, const char **argv)
37 {
38         TALLOC_CTX *mem_ctx;
39         size_t hint = 32;
40         pid_t pid;
41         int ret, lines = 0;
42         int pipefd[2];
43
44         if (argc < 2 || argc > 3) {
45                 fprintf(stderr, "Usage: %s <filename> [<hint>]\n", argv[0]);
46                 exit(1);
47         }
48
49         if (argc == 3) {
50                 long value;
51
52                 value = atol(argv[2]);
53                 assert(value > 0);
54                 hint = value;
55         }
56
57         ret = pipe(pipefd);
58         assert(ret == 0);
59
60         pid = fork();
61         assert(pid != -1);
62
63         if (pid == 0) {
64                 char buffer[16];
65                 ssize_t n, n2;
66                 int fd;
67
68                 close(pipefd[0]);
69
70                 fd = open(argv[1], O_RDONLY);
71                 assert(fd != -1);
72
73                 while (1) {
74                         n = read(fd, buffer, sizeof(buffer));
75                         assert(n >= 0 && (size_t)n <= sizeof(buffer));
76
77                         if (n == 0) {
78                                 break;
79                         }
80
81                         n2 = write(pipefd[1], buffer, n);
82                         assert(n2 == n);
83                 }
84
85                 close(pipefd[1]);
86                 close(fd);
87
88                 exit(0);
89         }
90
91         close(pipefd[1]);
92
93         mem_ctx = talloc_new(NULL);
94         assert(mem_ctx != NULL);
95
96         ret = line_read(pipefd[0], hint, NULL, line_print, NULL, &lines);
97         assert(ret == 0);
98
99         talloc_free(mem_ctx);
100
101         return lines;
102 }