Skip to content

Instantly share code, notes, and snippets.

@nagas
Last active May 15, 2018 16:09
Show Gist options
  • Save nagas/8eed060e90490157a58f7491aebfeaae to your computer and use it in GitHub Desktop.
Save nagas/8eed060e90490157a58f7491aebfeaae to your computer and use it in GitHub Desktop.
non blocking and without roundtrip to userspace
#define _GNU_SOURCE
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <limits.h>
int
main(int argc, char *argv[])
{
int len;
int devnull = open("/dev/null", O_WRONLY);
fd_set rfds;
do {
FD_ZERO(&rfds);
FD_SET(STDIN_FILENO, &rfds);
select(STDIN_FILENO+1, &rfds, NULL, NULL, 0);
if (FD_ISSET(STDIN_FILENO, &rfds)) {
len = splice(STDIN_FILENO, NULL, STDOUT_FILENO, NULL, INT_MAX, SPLICE_F_NONBLOCK);
if (len < 0) {
if (errno == EAGAIN) {
splice(STDIN_FILENO, NULL, devnull, NULL, INT_MAX, SPLICE_F_MOVE);
continue;
}
break;
}
}
} while (1);
close(devnull);
exit(EXIT_SUCCESS);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment