Skip to content

Instantly share code, notes, and snippets.

@dcoles
Last active September 24, 2016 05:03
Show Gist options
  • Save dcoles/e99c5e486f9f7c527efc64f29a0eac8e to your computer and use it in GitHub Desktop.
Save dcoles/e99c5e486f9f7c527efc64f29a0eac8e to your computer and use it in GitHub Desktop.
/**
* Print size and contents of a PIPE
* Author: David Coles <[email protected]>
*/
#define _GNU_SOURCE
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <unistd.h>
#include <termios.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#define ERROR(FORMAT, ...) do { fprintf(stderr, "ERROR: " FORMAT "\n", __VA_ARGS__); } while(0)
int main(int argc, char* argv[])
{
if (argc < 2) {
fprintf(stderr, "usage: %s PIPE\n", argv[0]);
return 2;
}
int fd = open(argv[1], O_RDONLY|O_NONBLOCK);
if (fd < 0) {
ERROR("open %s (%d)", strerror(errno), errno);
return 1;
}
int size = -1;
if (ioctl(fd, FIONREAD, &size) != 0) {
ERROR("ioctl(FIONREAD) %s (%d)", strerror(errno), errno);
close(fd);
return 1;
}
printf("%d\n", size);
if (size > 0) {
ssize_t sz = tee(fd, STDOUT_FILENO, (int)-1, SPLICE_F_NONBLOCK);
if (sz < 0) {
ERROR("tee %s (%d)", strerror(errno), errno);
}
}
close(fd);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment