有没有办法从 ps 命令结果中隐藏内核线程?

lov*_*ing 3 ps utilities proc linux-kernel

当我输入 时ps -ef,会显示许多特殊的内核线程进程。

我对内核线程不感兴趣;我只对用户进程/线程感兴趣。

有没有办法隐藏内核线程?

小智 5

ps可以通过多种方式过滤输出。要查看您的进程,您可以按用户/uid 进行过滤。下面的相关手册页-

   U userlist      Select by effective user ID (EUID) or name.
                   This selects the processes whose effective user name or ID is in userlist. The effective user ID describes the user
                   whose file access permissions are used by the process (see geteuid(2)). Identical to -u and --user.

   -U userlist     Select by real user ID (RUID) or name.
                   It selects the processes whose real user name or ID is in the userlist list. The real user ID identifies the user
                   who created the process, see getuid(2).

   -u userlist     Select by effective user ID (EUID) or name.
                   This selects the processes whose effective user name or ID is in userlist. The effective user ID describes the user
                   whose file access permissions are used by the process (see geteuid(2)). Identical to U and --user.
Run Code Online (Sandbox Code Playgroud)

要识别内核线程与用户线程,它可能取决于内核版本。在我的 Ubuntu 机器(3.5.0-30-generic)上,我可以通过排除 kthreadd 的子线程(pid = 2)来排除内核线程。kthreadd 的 pid 可能在 2.6 内核上有所不同 - 但是,您可以只使用相关的 pid。例如,要获取所有没有 ppid =2 的进程的列表,我会这样做(有关提供给 -o 的选项,请查看手册页)-

 ps -o pid,ppid,comm,flags,%cpu,sz,%mem  --ppid 2 -N
Run Code Online (Sandbox Code Playgroud)

您还可以使用 grep 或 awk 过滤这些。识别内核线程的另一种方法(不使用 ps)是检查 /proc//maps 或 /proc/cmdline 是否为空 - 对于内核线程来说两者都是空的。您需要 root 权限才能执行此操作。

  • 但是,这也隐藏了与其他用户一起运行的进程 (2认同)