如何在 Linux 下使用 C 获取有关进程状态的信息(即,如果它是僵尸)?
在阅读了到目前为止的答案之后,我想稍微缩小我的问题范围:我更喜欢纯 C 解决方案。在阅读了 ps 源代码(读取 /proc/)后,我认为应该有更好的方法并在这里问:)
如何在 Linux 下使用 C 获取有关进程状态的信息(即,如果它是僵尸)?
在阅读了到目前为止的答案之后,我想稍微缩小我的问题范围:我更喜欢纯 C 解决方案。在阅读了 ps 源代码(读取 /proc/)后,我认为应该有更好的方法并在这里问:)
您需要了解如何通过典型的 C 标准库调用与 /proc/“伪文件系统”进行交互。入门所需的文档包含在任何 Linux 发行版中,只需 google 搜索即可。
(现在您知道要搜索什么了。我知道这通常是最大的挑战!)
简而言之,正在运行的 Linux 系统的 /proc/ 目录中的目录和文件反映了正在运行的内核的状态,其中(自然)包括进程。但是,在您收费之前,您需要记住一些信息。
A zombie process isn't the same thing as an orphaned process. An orphaned process is a process left running in a waiting state after the process' parent has exited incorrectly. A zombie process is a process which has exited properly, released all its resources, but is maintaining a place in the process table.
This typically happens when a process is launched by a program. You see, the kernel won't remove a finished sub-process' entry in the process table until the parent program properly fetches the return status of the sub-process. That makes sense; how else would the parent program know if the subprocess exited improperly?
So all subprocesses are technically zombies for at least a very short time. It's not inherently a bad state for a program to be in.
Indeed, "zombies" are sometimes created intentionally. For example, sometimes a zombie entry is left in place by a program for a while so that further launched processes won't get the same PID as the previously-launched (and now zombie) process.
In other words, if you go SIGCHLDing zombie processes unnecessarily you might create a serious problem for the spawning program. However, if a process has been a zombie for a half hour or more, it's probably a sign of a bug.
Edit: The question changed on me! No, there's no simpler way than how ps does it. If there was, it would have been integrated into ps a long time ago. The /proc files are the be-all-end-all source for information on the kernel's state. :)
我只知道两种方法:
ps
命令的输出ps
内部执行的操作)您希望在您的机器上运行的进程然后使用
$ ps辅助
ps显示有关活动进程选择的信息。如果您想要重复更新选择和显示的信息,请改用top。
Pseudo file system /proc is describing kernel internal data structures and gives to you opportunity to alter some values directly. Obtaining state of particular process can be easily implemented with I/O C functions. The right file to parse is: /proc/{PID}/status
Command below can be used to obtain processes in Zombie state.
for proc in $(echo /proc/[0-9]*);do if [[ $(sed -n '/^State:\tZ/p' ${proc}/status 2>/dev/null) ]];then basename $proc;fi;done
在这里找到:
Use this command to display all of your zombie processes:
ps aux | awk '{ print $8 " " $2 }' | grep -w Z
这可以使用 C 轻松解析。