Hacker News new | ask | show | jobs
by kazinator 847 days ago
It supports the wacky semantics of the freopen function, which is probably why glibc implements freopen by opening /proc/self/fd/<n>.

Specifically, the case of freopen when the path argument is null, which was introduced in C99.

freopen does all the open-time actions such as that the "w" mode truncates the file. So that could be why. If we dup the descriptor, we have to call ftruncate to implement the "w" flag. I think if we just open the /proc item, O_TRUNC will do it for us.

The freopen function is wacky in the first place, and obviously the approach has the flaw that (as we learn from the submitted article) that sockets cannot be opened this way.

Obviously, /proc/.../fd was not designed for freopen.

/proc/<other-than-self>/fd is very useful for implementing, e.g. process substitution in Bash:

  $ diff -u <(this command) <(that command)
This calls diff with /proc/<pid>/fd/<n> /proc/<pid>/fd/<m> which refer to pipes set up by the shell. The diff program thinks it's just opening files.

/proc/self/fd/ exists because there is a /proc/self symlink to /proc/<self-pid>/ not necessarily because it's useful for a process to open its own descriptors this way. Other /proc/self things are useful, like /proc/self/exe to find out where your executable is located.

1 comments

I understand why it's useful to have access to another process' opened files.

I was wondering more why the Plan9 behavior would be useful - why you would want opening /proc/self/fd/<n> to give you a reference to the same file description instead of giving you a new file description. I assume opening /proc/<other-pid>/fd/<n> doesn't share file descriptions with the other process in Plan9 either, but maybe I'm assuming that wrongly as well.

If opening the other process' entry shares the description, that means you're messing with its read/write pointer.
I know, which is why I'm hoping that's not the case.

But then, if that's not the case for /proc/<other>/fd/<n>, why would it be for /proc/self/fd/<n> ? Where does this expectation come from?