1 #include "term.h"
2 #include <termios.h>
3 #include <unistd.h>
4 #include <poll.h>
5 #include <signal.h>
6 #include <stdlib.h>
7 
8 class canonical_termios_t
9 {
10  public:
canonical_termios_t()11   canonical_termios_t()
12    : restore_tios(false)
13   {
14     if (tcgetattr(0, &old_tios) == 0)
15     {
16       struct termios new_tios = old_tios;
17       new_tios.c_lflag &= ~(ICANON | ECHO);
18       if (tcsetattr(0, TCSANOW, &new_tios) == 0)
19         restore_tios = true;
20     }
21   }
22 
~canonical_termios_t()23   ~canonical_termios_t()
24   {
25     if (restore_tios)
26       tcsetattr(0, TCSANOW, &old_tios);
27   }
28  private:
29   struct termios old_tios;
30   bool restore_tios;
31 };
32 
33 static canonical_termios_t tios; // exit() will clean up for us
34 
read()35 int canonical_terminal_t::read()
36 {
37   struct pollfd pfd;
38   pfd.fd = 0;
39   pfd.events = POLLIN;
40   int ret = poll(&pfd, 1, 0);
41   if (ret <= 0 || !(pfd.revents & POLLIN))
42     return -1;
43 
44   unsigned char ch;
45   ret = ::read(0, &ch, 1);
46   return ret <= 0 ? -1 : ch;
47 }
48 
write(char ch)49 void canonical_terminal_t::write(char ch)
50 {
51   if (::write(1, &ch, 1) != 1)
52     abort();
53 }
54