How to find out if TTY Linux controls a process group

So, I have tty (let's say / dev / tty 5) and you want to know if it is currently managing tty for a process group or session, or if it is not currently in use. POSIX has two API functions that are offered here: tcgetpgrp () and tcgetsid (), which only work if the caller has tty as the control tty, which in this case makes them mostly useless (and actually I don’t know, t see . tcgetsid () clause in general).

Does anyone have a suggestion on how I can determine in a reasonable way, with C, whether the terminal is currently the process control terminal? I only care about Linux, so if you need Linux-specific APIs, that's fine with me.

+5
source share
4 answers

BSD: int ioctl (int tty, TIOCGETPGRP, int * foreground_group);

Linux: int tcgetpgrp (int tty, int * foreground_group);

Linux only works if you allow the use of a non-owner terminal, i.e. You are the root user. This is a deliberate security implementation. BSD ioctl () allows any tty to accept any process group (or even nonexisting process groups) as its foreground tty. POSIX only allows access to process groups for which tty is their control tty. This restriction prohibits some of the ambiguous security-related cases present in BSD ioctl.

? , , .

: /proc
www.die.net: /Proc/ []/FD , , , , . , 0 - , 1 , 2 ..

+1

"ps au > tempfile.txt" .

0

, , :

#include <stdlib.h>
#include <stdio.h>

int main()
{
  int status = system("fuser /dev/tty1 >/dev/null 2>/dev/null") >> 8;
  printf("%s",
         status ?
           "tty not in use as a text terminal.\n" :
           "tty in use as a text terminal.\n");
  return 0;
}
0

proc tty , PID .

/proc//fd/0 tty (say/dev/pts/4).

So all you have to do is create the proc path using the PID (for example: / proc / 7834 / fd / 0, where 7834 is the PID) and then call the readlink system call to get tty

See the C code snippet below.

sprintf(procPath, "/proc/%s/fd/0", pid);
int ret = readlink(procPath, buffer, MAX_LEN);
buffer[ret] = '\0';
0
source

All Articles