Skip to content

Avoid buffered I/O #4

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 9, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions fiber/fiber.c
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,26 @@
#include <sys/wait.h> /* For wait */
#include <unistd.h> /* 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 */
Expand Down