Tim
Tim

Reputation: 99526

How can we tell file descriptrs for controlling terminal from for noncontrolling terminal?

If a process has opened more than one terminals, how can we know which file descriptors are for the controlling terminals of the process' session, and which are for noncontrolling terminals?

Originated from https://unix.stackexchange.com/questions/446207/for-a-process-what-are-the-differences-between-a-controlling-terminal-and-non-c

Upvotes: 0

Views: 349

Answers (1)

zwol
zwol

Reputation: 140786

A process does not necessarily have any fds open on its controlling tty. However, if a process has a controlling terminal, it can open /dev/tty to get an fd for it. (If it doesn't have a controlling tty, opening /dev/tty will fail with, um, ENXIO, apparently, this isn't documented anywhere I can find, and honestly I would have expected ENODEV or ENOTTY instead, but it's consistent across Linux and NetBSD so it's probably an official spec somewhere.)

Learning whether an fd is open on the calling process's controlling tty is more difficult than it might seem. The obvious thing to do is, first, verify that it's open on some tty with isatty, and then call tcgetpgrp on it. tcgetpgrp is documented to fail if its fd argument does not refer to the calling process's controlling tty. Unfortunately, Linux at least also allows one to call tcgetpgrp on the outside of a pseudoterminal (this is what you get when you open /dev/ptmx), and I'm not having any luck finding a good way to distinguish an actual tty from the outside of a pseudoterminal; isatty will be true for both, most of the other terminal-related operations can be applied to both, and so on. You might have to resort to fstat and decoding st_rdev. Blech.

Upvotes: 4

Related Questions