]> git.proxmox.com Git - proxmox-mini-journalreader.git/commitdiff
use fwrite_unlocked instead of manually printing to buffer
authorDominik Csapak <d.csapak@proxmox.com>
Thu, 16 May 2019 10:22:18 +0000 (12:22 +0200)
committerThomas Lamprecht <t.lamprecht@proxmox.com>
Thu, 16 May 2019 14:48:58 +0000 (16:48 +0200)
this does the same as our old code, but is a lot shorter,
so it was uneccessary to have and the performance is the same
(no measureable difference)

we still need a wrapper to be sure that we wrote everything

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
src/mini-journalreader.c

index 15865921df4db12927471b8799d44cc847a72d5c..3be348e724565630876b8ae93e9ac57d8da5b1b7 100644 (file)
 #include <time.h>
 #include <unistd.h>
 
-#define BUFSIZE 4095
+#define BUFSIZE 4096
 
-static char buf[BUFSIZE + 1];
-static size_t offset = 0;
+static char BUF[BUFSIZE];
 
 static uint64_t get_timestamp(sd_journal *j) {
     uint64_t timestamp;
@@ -48,20 +47,12 @@ static void print_to_buf(const char * string, size_t length) {
     if (!length) {
         return;
     }
-    size_t string_offset = 0;
-    size_t remaining = length;
-    while (offset + remaining > BUFSIZE) {
-        strncpy(buf + offset, string + string_offset, BUFSIZE - offset);
-        string_offset += BUFSIZE - offset;
-        remaining = length - string_offset;
-        if (write (1, buf, BUFSIZE) <= 0) {
-            perror("write to stdout failed");
-            exit(1);
-        }
-        offset = 0;
+
+    size_t r = fwrite_unlocked(string, 1, length, stdout);
+    if (r < length) {
+       fprintf(stderr, "Failed to write\n");
+       exit(1);
     }
-    strncpy(buf + offset, string + string_offset, remaining);
-    offset += remaining;
 }
 
 static void print_cursor(sd_journal *j) {
@@ -272,6 +263,12 @@ int main(int argc, char *argv[]) {
         usage("unkown, or to many arguments");
     }
 
+    // setup stdout buffer
+    if (setvbuf(stdout, BUF, _IOFBF, BUFSIZE)) {
+       fprintf(stderr, "Failed to set buffer for stdout: %s\n", strerror(errno));
+       return 1;
+    }
+
     // to prevent calling it everytime we generate a timestamp
     tzset();
 
@@ -354,10 +351,7 @@ int main(int argc, char *argv[]) {
     sd_journal_close(j);
 
     // print remaining buffer
-    if (write (1, buf, offset) <= 0) {
-        perror("write to stdout failed");
-        return 1;
-    }
+    fflush_unlocked(stdout);
 
     return 0;
 }