Is it safe to parse a /proc/ file?

后端 未结 7 1393
终归单人心
终归单人心 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:49

    Short of unknown bugs, there are no race conditions in /proc that would lead to reading corrupted data or a mix of old and new data. In this sense, it's safe. However there's still the race condition that much of the data you read from /proc is potentially-outdated as soon as it's generated, and even moreso by the time you get to reading/processing it. For instance processes can die at any time and a new process can be assigned the same pid; the only process ids you can ever use without race conditions are your own child processes'. Same goes for network information (open ports, etc.) and really most of the information in /proc. I would consider it bad and dangerous practice to rely on any data in /proc being accurate, except data about your own process and potentially its child processes. Of course it may still be useful to present other information from /proc to the user/admin for informative/logging/etc. purposes.

提交回复
热议问题