an autoflusher
What if we want a grep that doesn’t stuck but we don’t want to resort to wild hacks like editing the source? What if there was some way to flush stdout automatically?
The auto flusher is a very simple preload.
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
static void *
flusher(void *arg)
{
while (1) {
sleep(3);
fflush(stdout);
}
}
__attribute__((constructor))
void
herewego(void)
{
pthread_t thread;
pthread_create(&thread, NULL, flusher, NULL);
}
Magic constructor attribute for initializers in C, and then we create a thread which loops around occasionally flushing stdout, so if there’s any data left lingering, it will eventually find it’s way out instead of waiting forever.
$ cc -shared -lpthread -o libflusher.so flusher.c
$ env LD_PRELOAD=./libflusher.so grep ...