Re:POSIX close(2) is broken
by antirez on Saturday December 17, 2011 @04:43AM
(#3363911)
This is a good example but more generally it is hardly possible to write serious long running and reliable software targeting posix in general...
[ Parent
| on HN ]
It isn't? The use of close(2) is the only place I'm aware of kivaloo assuming anything POSIX doesn't provide.
Just another example, among the infinite others: you fsycn a filedes in a thread, then write to the same fd from another thread, and write(2) will block. Tens of semantical behaviors like this are NOT part of POSIX, but are part of real world systems.
So anyway in order to write non trivial systems you have to understand the implementation of different system calls in different operating systems.
Re:POSIX close(2) is broken
by FooBarWidget on Saturday December 17, 2011 @06:09AM
(#3364012)
Now that I think about it, dup2() to an existing file descriptor must be broken in a similar manner. In fact, with dup2() you can't even figure out whether the implicit close() succeeded.
Re:POSIX close(2) is broken
by FrankBooth on Saturday December 17, 2011 @06:19AM
(#3364029)
From the man page:
If newfd was open, any errors that would have been reported at close(2) time are
lost. A careful programmer will not use dup2() or dup3() without closing newfd
first.Which is actually "interesting" advice, as it cannot be followed in a multithreaded program without insanely extensive process-wide locks ;P (as any call to open() between close() and dup2() has an irritatingly high probability of grabbing whatever file descriptor you just freed up). (Of course, most usages of dup2() are in contexts just after a fork() or at the beginning of main(), so I guess this could often be practical; it still seems unfortunate.)
Maybe this can still be worked around by copying the target fd first so it can be closed after fdup()ing the source fd, e.g.
// Assume x and y are open fds and we want to replace y with a copy of x
z = open("/dev/null", O_RDONLY); // Guarantees no other thread is using z
dup2(y, z);
dup2(x, y);
close(z);
Hah! (You don't actually need that open("/dev/null") trick, though: you can just use dup(). ;P)