5

所以我有一个 tty(比如说 /dev/tty5)并且想知道它当前是否是进程组或会话的控制 tty,或者它当前是否是无主的。POSIX 有两个 API 函数,它们在这里建议自己:tcgetpgrp() 和 tcgetsid(),但这两个函数都只有在调用者将 tty 作为控制 tty 时才有效——在这种情况下,这使它们几乎无用(实际上我没有根本看不到 tcgetsid() 的意义)。

有人建议我如何从 C 中以理智的方式检测终端当前是否是进程的控制终端?我只关心 Linux,所以如果需要特定于 Linux 的 API,那对我来说没问题。

4

4 回答 4

1

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

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

Linux 只有在您拥有非拥有终端的权限时才能工作,即您是 root。这是一个有意的安全实施。BSD ioctl() 允许任何 tty 将任何进程组(甚至不存在的进程组)作为其前台 tty。POSIX 只允许访问以 tty 作为其控制 tty 的进程组。此限制不允许 BSD ioctl 中存在一些模棱两可和破坏安全的情况。

你想做什么?如果您是传递信号的内核,您应该只担心进程控制 tty。

编辑:我忘记了 /proc
来自 www.die.net:/proc/[number]/fd 这是一个子目录,其中包含进程打开的每个文件的一个条目,由其文件描述符命名,它是指向的符号链接实际文件。因此,0 是标准输入,1 是标准输出,2 是标准错误,等等。

于 2010-07-06T20:48:49.870 回答
0

you can use the proc file system to query the controlling tty of a process, if you know the PID of the process.

/proc//fd/0 is a symbolic link to the tty (say /dev/pts/4).

So all you need to do is create a proc path with the PID (eg: /proc/7834/fd/0, where 7834 is the PID) and then call the readlink system call to get the tty

See the C code snippet below

sprintf(procPath, "/proc/%s/fd/0", pid);
int ret = readlink(procPath, buffer, MAX_LEN);
buffer[ret] = '\0';
于 2010-07-28T08:03:02.000 回答
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;
}
于 2010-07-11T22:14:41.590 回答
0

将其作为系统调用“ps au >tempfile.txt”执行,并解析文件。

于 2010-07-07T20:15:21.130 回答