如何从 /proc 目录读取所有后台进程?

How to read all background processes from /proc directory?

我想获取 OS 中所有后台进程的列表 运行。作业命令完成工作。但我正在使用 C 来完成任务。主要问题是,如何使用 /proc/{pid} 中的状态文件区分后台进程和前台进程。

后台进程是进程组的成员进程,该进程组在其控制终端上不是前台进程组

来自/proc/PID/stat的相应字段是:

          (5) pgrp  %d
                    The process group ID of the process.
          (8) tpgid  %d
                    The ID of the foreground process group of the control‐
                    ling terminal of the process.

因此对于后台进程,这些字段将有所不同。 (3) state(7) tty_nr(6) session.

也很有用

(字段编号从 1 开始)

以下将打印(当 运行 来自启用作业控制的交互式 shell 时)当前会话中所有未停止的后台进程:

awk -vsid=$$ '==sid && !="T" && != {print , }' /proc/[0-9]*/stat

为简单起见,假设进程名称(括号中的第二个字段)不包含 space;你必须首先在括号上分割线,然后在 space.

上分割线来处理这个问题

另请注意,这还将打印从子 shell 开始的进程,这些进程不在 shell 的作业 table 中(例如 (sleep 3600 &))。