This makes it easier to test error paths, too.
* if (fd < 0)
* err(1, "Accepting connection on TCP socket");
*
- * oserver_serve(fd);
+ * if (!oserver_serve(fd))
+ * err(1, "Serving client");
+ * exit(0);
* }
*/
int main(int argc, char *argv[])
return 1;
if (strcmp(argv[1], "depends") == 0) {
- printf("ccan/compiler\n");
printf("ccan/read_write_all\n");
printf("ccan/str\n");
printf("ccan/foreach\n");
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
+#include <errno.h>
-void oserver_serve(int fd)
+bool oserver_serve(int fd)
{
char buf[1024];
unsigned int i;
for (i = 0; i < sizeof(buf)-1; i++) {
- if (read(fd, &buf[i], 1) != 1)
- errx(1, "Client disconnected");
+ if (read(fd, &buf[i], 1) != 1) {
+ errno = EIO;
+ return false;
+ }
if (buf[i] == '\n' || buf[i] == '\r')
break;
buf[i] = toupper(buf[i]);
strlen("Louder, like this: '"))
|| !write_all(fd, buf, i)
|| !write_all(fd, "'\r\n", strlen("'\r\n")))
- err(1, "Write failed");
- exit(0);
+ return false;
+ return true;
}
int oserver_setup(void)
#ifndef CCAN_OSERVER_H
#define CCAN_OSERVER_H
-#include <ccan/compiler/compiler.h>
+#include <stdbool.h>
/**
* oserver_setup - get a listening filedescriptor for an oserver
* oserver_serve - serve an oserver client via a file descriptor
* @fd: the file descriptor (usually a connected socket)
*
- * This does not return, but exits with status 0 if served OK.
+ * This returns false (with errno set) on failure.
*
* Example:
* #include <sys/types.h>
* if (clientfd < 0)
* err(1, "Accepting connection from client");
* if (fork() == 0)
- * oserver_serve(clientfd);
+ * exit(oserver_serve(clientfd) ? 0 : 1);
* else
* close(clientfd);
*/
-void NORETURN oserver_serve(int fd);
+bool oserver_serve(int fd);
#define OSERVER_PORT 2727
#endif /* CCAN_OSERVER_H */
int main(void)
{
int fd;
- int status;
char buf[200];
const char *input;
/* This is how many tests you plan to run */
- plan_tests(4 * 6);
+ plan_tests(3 * 6);
foreach_ptr(input,
"This is a test\n",
write(fd, input, strlen(input));
lseek(fd, 0, SEEK_SET);
- if (fork() == 0)
- oserver_serve(fd);
-
- wait(&status);
-
- ok1(WIFEXITED(status));
- ok1(WEXITSTATUS(status) == 0);
+ ok1(oserver_serve(fd));
lseek(fd, 0, SEEK_SET);
buf[read(fd, buf, sizeof(buf)-1)] = '\0';