function to Get the terminal file descriptor of the current process UNIX

Tag: unix Author: zjhthefirst Date: 2009-09-17

I want to use function:

pid_t tcgetpgrp(int fildes);

How to retrieve the fildes(to be passed to this function).

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

getpgrp(0)//0 for the calling process


Best Answer

You can pass any file descriptor that is open to a terminal; the call will retrieve the information about that terminal. A process may have file descriptors open to a number of terminals, but at most one of those is the process's controlling terminal. A given terminal may, in fact, have no process group associated with it for which it is the controlling terminal (though it is relatively unlikely to be opened in that case).

Michiel Buddingh' suggested STDIN_FILENO from <unistd.h> (which is normally a fancy way of writing 0); the trouble with that is that programs can have standard input redirected from a file or have the input piped to it, in which cases the standard input is not a terminal. Similar considerations apply to STDOUT_FILENO (aka 1). The best descriptor to use, therefore, is often STDERR_FILENO (aka 2); that is the least likely to be redirected.

The second half of the question is 'does tcgetpgrp() return the same value as getpgrp()'. The answer is 'No'. Every process belongs to a process group, and getpgrp() will reliably identify that group. Not every process has a controlling terminal, and not every file descriptor identifies a terminal, so tcgetpgrp() can return the error ENOTTY. Further, when tcgetpgrp() does return a value, it is the value of the current foreground process group associated with the terminal, which is explicitly not necessarily the same as the process group of the current process, which may be part of a background process group associated with the terminal. The current foreground process group can change over time, too.

Other Answer1

Often standard input, output, and/or error (0, 1, or 2) will be connected to the controlling terminal. To be sure 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 if it is no longer needed.

The tcgetpgrp() function returns the foreground process group id, whereas getpgrp() returns your process group id. They would be the same if your process is in the foreground, or different if your process is in the background. tcgetpgrp() would return an error if your process had no controlling terminal, and is therefore not in the foreground or background.

Other Answer2

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