Skip to content

Instantly share code, notes, and snippets.

@takaswie
Created August 26, 2017 09:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save takaswie/d31e49598b06133eeeec2814237126e9 to your computer and use it in GitHub Desktop.
Save takaswie/d31e49598b06133eeeec2814237126e9 to your computer and use it in GitHub Desktop.
stdin v.s. tty
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <poll.h>
#include <termios.h>
int main(void)
{
char buf[1024];
int len;
int i, j;
struct pollfd pfds[2] = {0};
struct termios flags = {0};
pfds[1].fd = open("/dev/tty", O_RDONLY);
if (pfds[1].fd < 0) {
printf("open(2): %s\n", strerror(errno));
return EXIT_FAILURE;
}
pfds[1].events = POLLIN;
if (tcgetattr(pfds[1].fd, &flags) < 0) {
printf("tcgetattr(3): %s\n", strerror(errno));
close(pfds[1].fd);
return EXIT_FAILURE;
}
flags.c_lflag &= ~ICANON;
if (tcsetattr(pfds[1].fd, TCSANOW, &flags) < 0) {
printf("tcsetattr(3): %s\n", strerror(errno));
close(pfds[1].fd);
return EXIT_FAILURE;
}
pfds[0].fd = fileno(stdin);
if (pfds[0].fd < 0) {
printf("open(2): %s\n", strerror(errno));
close(pfds[1].fd);
return EXIT_FAILURE;
}
pfds[0].events = POLLIN;
while (1) {
for (i = 0; i < sizeof(pfds)/sizeof(pfds[0]); ++i)
pfds[i].revents = 0;
len = poll(pfds, sizeof(pfds)/sizeof(pfds[0]), -1);
if (len < 0) {
if (errno == -EAGAIN)
continue;
printf("poll(2): %s\n", strerror(errno));
break;
}
if (len == 0)
continue;
for (i = 0; i < sizeof(pfds)/sizeof(pfds[0]); ++i) {
if (!(pfds[i].revents & POLLIN))
continue;
len = read(pfds[i].fd, buf, sizeof(buf));
if (len < 0) {
printf("read(2): %s\n", strerror(errno));
break;
}
if (len == 0)
break;
for (j = 0; j < len; ++j) {
printf("%d: %d: %c\n", pfds[i].fd, j, buf[j]);
fflush(stdout);
}
}
}
flags.c_lflag |= ICANON;
if (tcsetattr(pfds[0].fd, TCSANOW, &flags) < 0) {
printf("tcsetattr(3): %s\n", strerror(errno));
close(pfds[0].fd);
return EXIT_FAILURE;
}
close(pfds[0].fd);
close(pfds[1].fd);
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment