Is it safe to parse a /proc/ file?

后端 未结 7 1380
终归单人心
终归单人心 2020-12-12 09:53

I want to parse /proc/net/tcp/, but is it safe?

How should I open and read files from /proc/ and not be afraid, that some other process (o

7条回答
  •  伪装坚强ぢ
    2020-12-12 10:41

    /proc is a virtual file system : in fact, it just gives a convenient view of the kernel internals. It's definitely safe to read it (that's why it's here) but it's risky on the long term, as the internal of these virtual files may evolve with newer version of kernel.

    EDIT

    More information available in proc documentation in Linux kernel doc, chapter 1.4 Networking I can't find if the information how the information evolve over time. I thought it was frozen on open, but can't have a definite answer.

    EDIT2

    According to Sco doc (not linux, but I'm pretty sure all flavours of *nix behave like that)

    Although process state and consequently the contents of /proc files can change from instant to instant, a single read(2) of a /proc file is guaranteed to return a ``sane'' representation of state, that is, the read will be an atomic snapshot of the state of the process. No such guarantee applies to successive reads applied to a /proc file for a running process. In addition, atomicity is specifically not guaranteed for any I/O applied to the as (address-space) file; the contents of any process's address space might be concurrently modified by an LWP of that process or any other process in the system.

提交回复
热议问题