Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

get fd of terminal when a destination of pipe

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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).)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading