#define _GNU_SOURCE
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <dlfcn.h>
#include <sys/time.h>
#include <sys/select.h>
#include <sys/stat.h>
#include <errno.h>
#if defined(__NetBSD__)||defined(__FreeBSD__)||defined(__DragonFly__)||defined(__APPLE__)
#define PN getprogname()
#else
#define PN program_invocation_short_name
#endif
static ssize_t (*rw)(int,const void*,size_t);
__attribute__((constructor)) static void ini(void)
{
  rw = (ssize_t(*)(int, const void*, size_t)) dlsym(RTLD_NEXT,"write");
}

#define SLEEP_US 10000
ssize_t write(int fd,const void*b,size_t n)
{
    if (!rw)
    {
        errno = ENOSYS;
        return -1;
    }

    struct stat s;
    struct timeval t = {0, SLEEP_US};
    if (PN && strstr(PN, "perl") && fstat(fd, &s) == 0 && S_ISFIFO(s.st_mode))
        select(0, 0, 0, 0, &t);

    return rw(fd, b, n);
}
