From 72264516529dae8e7201e9927b9d3b7c6f0d61b5 Mon Sep 17 00:00:00 2001 From: RinHizakura Date: Tue, 8 Jun 2021 14:35:05 +0800 Subject: [PATCH] Add unbuffered print for fiber A simple solution to avoid unexpected output by the buffered I/O 'printf' is using low-level I/O interface 'write'. It works because 'printf' will wait to write to STDOUT until the buffer is full, or on some other conditions. Using write, however, can write to STDOUT immediately. Here is a naive implementation for the idea with some limitation and weakness that need improvement: 1. It will fail if the formatted string with length >64 2. The function 'write' can write less than n bytes. It will need further handling if happens. --- fiber/fiber.c | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/fiber/fiber.c b/fiber/fiber.c index cabf9c4..7dda871 100644 --- a/fiber/fiber.c +++ b/fiber/fiber.c @@ -19,6 +19,26 @@ #include /* For wait */ #include /* For getpid */ +/* A simple solution to avoid unexpected output by the buffered I/O 'printf' is + * using low-level I/O interface 'write'. It works because 'printf' will wait to + * write to STDOUT until the buffer is full, or on some other conditions. Using + * write, however, can write to STDOUT immediately. + * + * Here is a naive implementation for the idea with some limitation and weakness + * that need improvement: + * 1. It will fail if the formatted string with length >64 + * 2. The function 'write' can write less than n bytes. It will need further + * handling if happens. + */ +#define BUF_LEN 64 +#define printf_unbuffered(fmt, ...) \ + do { \ + char str[BUF_LEN + 1]; \ + int n = snprintf(str, BUF_LEN + 1, fmt __VA_OPT__(, ) __VA_ARGS__); \ + write(1, str, n); \ + } while (0) +#define printf printf_unbuffered + typedef struct { pid_t pid; /* The pid of the child thread as returned by clone */ void *stack; /* The stack pointer */