C 中的 tcgetpgrp 函数

tcgetpgrp function in C

语法:

   pid_t tcgetpgrp(int fd);

在手册页中:

The function tcgetpgrp() returns the process group ID of the foreground process group on the terminal associated to fd, which must be the controlling terminal of the calling process.`

所以,利用这个函数我们可以获取终端的前台进程。但是我不明白哪个文件描述符传递给了这个函数。传递给这个函数的文件描述符有什么用,为什么?

你可以这样称呼它:

#include <unistd.h>

pid_t pid = tcgetpgrp(STDIN_FILENO);

The Open Group 基础规范第 6 期 IEEE 标准 1003.1,2004 版说:

11.1.2 Process Groups

A terminal may have a foreground process group associated with it. This foreground process group plays a special role in handling signal-generating input characters, as discussed in Special Characters.

tcgetpgrp 是可以返回附加到给定终端的该组 ID 的函数。该参数必须是与终端关联的文件描述符,不仅如此,它还必须是进程控制终端的描述符:

11.1.3 The Controlling Terminal

A terminal may belong to a process as its controlling terminal. Each process of a session that has a controlling terminal has the same controlling terminal.

简而言之,控制终端是让您管理作业的对象 shell :发送 CTRL-Z 暂停作业,将作业设为前台,使用 CTRL-C 取消作业等等。一个控制终端可以让你控制连接到这个终端的进程组。这个控制可能包括:终端的并发访问、会话管理、foreground/background等

ctermid 可能会给你控制终端的路径(tty 命令行也一样)。请注意,控制终端可能与您制作标准 I/Os 的终端不同,但通常是相同的。然后,您可以(非常普遍地)使用 STDIN_FILENO(以及其他两个)。您还可以使用 isatty 来确定文件描述符是否与终端关联。