Skip to content

Commit 521032e

Browse files
committed
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 STDOUT until the buffer is full, or on some other conditions. Using write, however, can write 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.
1 parent 41be11a commit 521032e

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

fiber/fiber.c

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,26 @@
1919
#include <sys/wait.h> /* For wait */
2020
#include <unistd.h> /* For getpid */
2121

22+
/* A simple solution to avoid unexpected output by the buffered I/O 'printf' is
23+
* using low-level I/O interface 'write'. It works because 'printf' will wait to
24+
* write STDOUT until the buffer is full, or on some other conditions. Using
25+
* write, however, can write STDOUT immediately.
26+
*
27+
* Here is a naive implementation for the idea with some limitation and weakness
28+
* that need improvement:
29+
* 1. It will fail if the formatted string with length >64
30+
* 2. The function 'write' can write less than n bytes. It will need further
31+
* handling if happens.
32+
*/
33+
#define BUF_LEN 64
34+
#define printf_unbuffered(fmt, ...) \
35+
do { \
36+
char str[BUF_LEN + 1]; \
37+
int n = snprintf(str, BUF_LEN + 1, fmt __VA_OPT__(, ) __VA_ARGS__); \
38+
write(1, str, n); \
39+
} while (0)
40+
#define printf printf_unbuffered
41+
2242
typedef struct {
2343
pid_t pid; /* The pid of the child thread as returned by clone */
2444
void *stack; /* The stack pointer */

0 commit comments

Comments
 (0)