#include <termios.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
static void usage(void)
{
fputs(
"usage:\n"
" tool <n>\n"
"copies stdin to stdout, and inserts a newline after every byte.\n"
"If no character is available on stdin for <n>/10 seconds, a bare newline\n"
"is inserted.\n", stderr);
exit(42);
}
static void bumm(void)
{
perror("tool");
exit(42);
}
int main(int argc, char *argv[])
{
int tenth_seconds;
char buf[2];
struct termios tbuf;
int red;
if (argc != 2) usage();
sscanf(argv[1], "%d", &tenth_seconds);
if (tcgetattr(0, &tbuf) < 0)
bumm();
/* switch off echo and line-by-line processing */
tbuf.c_lflag &= ~(ICANON | ECHO);
/* read will return after reading one byte or waiting <tenth_seconds>
Zehntelsekunden. */
tbuf.c_cc[VMIN] = 0;
tbuf.c_cc[VTIME] = tenth_seconds;
if (tcsetattr(0, TCSAFLUSH, &tbuf) < 0)
bumm();
buf[1] = '\n';
while (1) { /* forever */
red = read(0, buf, 1); /* one char from stdin */
if (red == 1) {
write(1, buf, 2); /* write char + newline */
} else if (red == 0) {
write(1, buf+1, 1); /* a single newline */
} else {
bumm();
}
}
}