如何判断一个进程是否在前台运行(Linux)?

How to judge whether a process is running in the foreground(Linux)?

最近我一直在尝试在 c 中实现作业控制 shell 并且遇到了上述问题。

当我输入命令时,它会在前台执行,同时在它完成之前我不能对终端做任何事情,换句话说,它控制着终端。

回到问题,gnu 文档给出了一个展示,其中它测试 stdin_fileno 是否是一个 tty。这是我的问题:

  1. 这是否意味着当一个进程 运行 在前台时它也在控制终端?如果不是有什么区别?
  2. 无论如何,Stdin fileno 是一个微型文件。为什么进程之间会有所不同?

Recently I've been trying to implement a Job control shell in c and I got the above question The gnu documents give a showcase in which it tests whether stdin_fileno is a tty.

我想你的意思是 the section of the Glibc manual describing the implementation of a job-control shell。如果没有,那绝对是您应该阅读的内容。

Here is my question: does this means that when a process is running in the foreground it is also controlling the terminal?

没有。虽然每个终端都有一个控制进程,但与前台和后台关系不大。我们通常对进程的控制终端更感兴趣——也就是说,在某种意义上控制进程的终端,而不是相反。前景和背景与后一个概念有关。

属于终端前台进程组的进程可以从该终端读取和写入。其他进程无法成功这样做 -- 如果他们尝试,他们将被阻止或暂停。

If not what's the difference? I realize there could be a group of process running in the foreground as a job, so in this case which process exactly controls the terminal?

给定终端的前台进程组中的所有进程都可以从终端读取和写入。它们不需要是终端的控制进程来这样做,而且它们通常不是。但是他们通常将终端作为他们的控制终端。

关于问题更新:

When I type a command it gets executed in the foreground, at the same time I could not do anything to the terminal until it finish, in other words, it controls the terminal.

描述作为控制终端的进程是令人担忧的,特别是从实现shell的角度来看,因为它是前台vs的表现。背景,而不是终端的“控制过程”。前台进程组中的进程(通常)不 control 终端,而是对其有特殊的 access。作业控制 shell 的部分工作是调解该访问。