问题描述
我想从 /proc
目录中检索一些进程信息,我的问题如下:/proc/PID
中的文件是否有标准格式?
例如,这个 proc/PID/status
文件的第一行带有 Name:'\t'ProcName
.我可以在其他地方用空格代替 \t
或类似的东西来遇到这个文件吗?
I want to retrieve some process info from /proc
directory and my question is the following: is there a standart format for files in /proc/PID
?
For example, there is this proc/PID/status
file with Name:'\t'ProcName
in its first line. Can I meet this file elsewhere with a whitespace instead of \t
or smth like that?
推荐答案
首先,Linux 中 /proc
的文档在 Linux 源代码中提供,在 Documentation/filesystems/proc.txt
.如果要使用 procfs,那应该是您首先要考虑的地方.遗憾的是,AFAICS 没有提到确切的记录格式.
First of all, the documentation on /proc
in Linux is provided in the Linux sources, in Documentation/filesystems/proc.txt
. That should be the first place you look into if going to work with procfs. Sadly, AFAICS it doesn't mention the exact record format.
第二个要查看的地方是procps
源代码(即提供ps
工具的包).在那里你可以找到:
The second place to look is procps
sources (that is, the package which provides ps
tool). There you can find:
colon = strchr(S, ':');
if(unlikely(!colon)) break;
if(unlikely(colon[1]!='\t')) break;
这意味着 ps
依赖于 :\t
存在.因此,您可以假设当前所有的 Linux 内核都使用这种格式.此外,我怀疑细微的更改(例如用其他东西替换 \t
)是否会被认为足以破坏与旧版本 ps
工具的兼容性.
which means that ps
relies on the :\t
being there. Therefore, you can assume that all current Linux kernels use this format. Moreover, I doubt that minor changes (like replacing the \t
with something else) would be considered important enough to break compatibility with the old versions of ps
tool.
也就是说,您通常可以更自由地接受.考虑到该文件的具体内容,您可以假设冒号是字段分隔符,并去除其后的任何空格.如果您使用的是 shell 脚本,那么常规的字段分隔就足够了.
That said, you can usually be more liberal in what you accept. Considering the specific contents of that file, you can assume the colon being field separator, and strip any whitespace following it. If you are using shell script, the regular field separation should suffice.
最后,我想说几点:
status
文件应该是人类可读的.因此,程序通常更好地读取stat
文件,而不是设计为面向机器的.- 我在这里只考虑 Linux(基于标签).不同的系统可能有一些不同的
/proc
格式. - 如果您正在编写 C 程序(shell 标签是由编辑器添加的),您应该考虑使用
procpslibprocps
库/code> 而不是手动读取文件.这样,您就可以避免重新发明轮子和直接依赖特定格式.
- The
status
file is supposed to be human-readable. Therefore, programs are usually better reading thestat
file instead which is designed to be machine-oriented. - I am considering Linux here only (based on tags). Different systems may have a bit different
/proc
format. - If you are writing a C program (the shell tag was added by an editor), you should consider using the
libprocps
library which comes withprocps
instead of reading the files by hand. That way, you avoid re-inventing the wheel and relying on a specific format directly.
这篇关于/proc/PID 文件的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!