suck.c - src - atrocities - clsr.net

/*
 * This software is released into the public domain.
 * It is provided "as is", without warranties or conditions of any kind.
 * Anyone is free to use, modify, redistribute and do anything with this software.
 *
 * suck.c: applies strong suction to its output stream causing data to backflow into the input stream
 * usage:  suck <output >>input
 */

/* truncate stdin file */
#define TRUNCATE 0

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

void checkerr(int ret)
{
	if (ret < 0) {
		perror("");
		exit(1);
	}
}

void fname(int fd, char *buf, size_t len)
{
	char path[0xff];
	ssize_t n;

	sprintf(path, "/proc/self/fd/%d", fd);
	checkerr(n = readlink(path, buf, len));
	buf[n] = 0;
}

int main(void)
{
	char fin[0xfff], fout[0xfff];
	int fdin, fdout;
	char buf[1024*8];
	ssize_t n;

	fname(STDIN_FILENO, fin, sizeof(fin));
	fname(STDOUT_FILENO, fout, sizeof(fout));

	checkerr((fdin = open(fout, O_RDONLY)));
	checkerr((fdout = open(fin, O_WRONLY | ((!TRUNCATE)*O_APPEND))));

	checkerr(dup2(fdin, STDIN_FILENO));
	checkerr(dup2(fdout, STDOUT_FILENO));

	while ((n = read(STDIN_FILENO, buf, sizeof(buf)))) {
		checkerr(n);
		write(STDOUT_FILENO, buf, n);
	}

	return 0;
}