[ccan] [PATCH v2 06/13] configurator: Print test source without cat

Kevin Locke kevin at kevinlocke.name
Fri Sep 23 13:33:09 AEST 2016


Windows does not provide cat.  Instead, copy the test source to stdout
using the file stream to which it was written.

Changes since v1:
- Create fwrite_noeintr to avoid EINTR in fwrite without writing any
  data.
- Handle short reads from fread.  This can happen with non-conformant
  libc or if EINTR occurs after reading some data.
- Handle short writes from fwrite.  This can happen with non-conformant
  libc or if EINTR occurs after writing some data.

Signed-off-by: Kevin Locke <kevin at kevinlocke.name>
---
 tools/configurator/configurator.c | 48 +++++++++++++++++++++++++++++++++++----
 1 file changed, 43 insertions(+), 5 deletions(-)

diff --git a/tools/configurator/configurator.c b/tools/configurator/configurator.c
index 31e3d11..51d7ac8 100644
--- a/tools/configurator/configurator.c
+++ b/tools/configurator/configurator.c
@@ -438,6 +438,42 @@ static size_t fread_noeintr(void *ptr, size_t size, size_t nitems,
 	return ret;
 }
 
+static size_t fwrite_noeintr(const void *ptr, size_t size, size_t nitems,
+		FILE *stream)
+{
+	size_t ret;
+
+	do {
+		errno = 0;
+		ret = fwrite(ptr, size, nitems, stream);
+	} while (ret == 0 && errno == EINTR);
+
+	return ret;
+}
+
+static size_t fcopy(FILE *fsrc, FILE *fdst)
+{
+	char buffer[BUFSIZ];
+	size_t copied = 0, rsize;
+
+	while ((rsize = fread_noeintr(buffer, 1, BUFSIZ, fsrc)) > 0) {
+		size_t wsize, wtotal = 0;
+
+		while (wtotal < rsize &&
+		       ((wsize = fwrite_noeintr(buffer + wtotal, 1,
+						rsize - wtotal, fdst)) > 0)) {
+			wtotal += wsize;
+		}
+
+		if (wtotal < rsize)
+			break;
+
+		copied += wtotal;
+	}
+
+	return copied;
+}
+
 static char *grab_stream(FILE *file)
 {
 	size_t max, ret, size = 0;
@@ -562,7 +598,7 @@ static bool run_test(const char *cmd, struct test *test)
 		}
 	}
 
-	outf = fopen(INPUT_FILE, "w");
+	outf = fopen(INPUT_FILE, verbose > 1 ? "w+" : "w");
 	if (!outf)
 		err(1, "creating %s", INPUT_FILE);
 
@@ -593,11 +629,13 @@ static bool run_test(const char *cmd, struct test *test)
 		abort();
 
 	}
-	fclose(outf);
 
-	if (verbose > 1)
-		if (system("cat " INPUT_FILE) == -1)
-			;
+	if (verbose > 1) {
+		fseek(outf, 0, SEEK_SET);
+		fcopy(outf, stdout);
+	}
+
+	fclose(outf);
 
 	newcmd = strdup(cmd);
 
-- 
2.9.3



More information about the ccan mailing list