File tree Expand file tree Collapse file tree 1 file changed +20
-0
lines changed Expand file tree Collapse file tree 1 file changed +20
-0
lines changed Original file line number Diff line number Diff line change 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 to STDOUT until the buffer is full, or on some other conditions. Using
25+ * write, however, can write to 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+
2242typedef struct {
2343 pid_t pid ; /* The pid of the child thread as returned by clone */
2444 void * stack ; /* The stack pointer */
You can’t perform that action at this time.
0 commit comments