Function Get the terminal file descriptor of the current UNIX process

I want to use a function:

pid_t tcgetpgrp(int fildes);

      

How to get fields (for passing this function).

And the process group id returned by this function is the same as returned

getpgrp(0)//0 for the calling process

      

??

+2


source to share


3 answers


You can pass any file descriptor open to the terminal; the call will receive information about this terminal. A process can have file descriptors open to multiple terminals, but at most one of them is the process control terminal. In fact, a given terminal does not have an associated process group for which it is the controlling terminal (although in this case it is unlikely to be open).

Michiel Buddingh suggested STDIN_FILENO

from <unistd.h>

(which is usually a fancy way of writing 0); the problem is that programs can have standard input redirected from a file, or an input pipe to it, in which case the standard input is not a terminal. Similar considerations apply to STDOUT_FILENO

(aka 1). Therefore the best descriptor to use is often STDERR_FILENO

(aka 2); this is the least likely redirect.



Second half of the question: ' tcgetpgrp()

returns the same value as getpgrp()

'. The answer is no. ' Each process belongs to a process group and getpgrp()

reliably identifies that group. Not every process has a controlling terminal, and not every file descriptor identifies a terminal, so it tcgetpgrp()

might return an ENOTTY error. In addition, when tcgetpgrp()

returned, it is the value of the current foreground process group associated with the terminal, which does not explicitly necessarily match the current process group process, which may be part of the background process of the terminal associated group. The current foreground process group can also change over time.

+3


source


Typically, standard input, output, and / or error (0, 1, or 2) are connected to the control terminal. To just open / dev / tty, which will always be the controlling terminal if you have one. The file descriptor returned from open () can be passed to tcgetpgrp () and then closed when no longer needed.



Tcgetpgrp () returns the foreground group ID, while getpgrp () returns the process group ID. They will be the same if your process is in the foreground, or different if your process is in the background. tcgetpgrp () will return an error if your process does not have a controlling terminal and therefore is not in the foreground or background.

+5


source


You need the file descriptor number attached to the current terminal. For example, you can use 0 or STDIN_FILENO

from unistd.h

.

0


source







All Articles