Home > Blockchain >  get fd of terminal when a destination of pipe
get fd of terminal when a destination of pipe

Time:12-26

My program (a text editor) enters raw mode of terminal like this:

tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw)

so that it can read key strokes, draw using escape codes etc.

But now I want to do this: echo hello | myprog, to read stdin from a pipe and then display it in the program UI. But now STDIN_FILENO points to a pipe not to a terminal and tcsetattr fails with improper ioctl. How do I get fd of an actual terminal when being a destination of a pipe?

CodePudding user response:

Usually, /dev/tty is the current console, and if you don't need stdio interfaces, you can open it, receiving a fd, with int ttyfd = open("/dev/tty", O_RDWR). (It's usually a bad idea to mix Unix I/O and stdio I/O on the same device. But if you really want to, open with FILE* ftty = fopen("/dev/tty", "rw"); and get the fd out of the FILE* with fileno(ftty).)

  • Related