4 ms·
Here's a couple of other bad options: * Create an empty temporary file and set a fcntl(F_SETLK) lock on the whole thing. Those locks don't get inherited to chi
by geofft 11y ago
Here's a couple of other bad options:
* Create an empty temporary file and set a fcntl(F_SETLK) lock on the whole thing. Those locks don't get inherited to child processes. Use fcntl(F_GETLK) to see if you can re-set that lock: if you can, you must be in the same process.
The downside of this approach is that it involves a file descriptor, and lots of post-fork code tends to like doing a `for i in 0..MAXFD {close(i);}` loop. You could instead store a path to the temporary file in global memory, but that might be more expensive than you'd like.
* Fork a child that sits around forever, e.g. on pause(). Then try to waitpid(WNOHANG) on it. If that returns ECHILD, you're no longer the parent of that child. I think this is reliable and portable, but incredibly ugly.
Sadly the kernel keyring option is looking like a better one than both of these.
- geocar 11y agoYou're still doing a syscall in both approaches in the best-case scenario. Mine wastes a syscall in the worst-case scenario and always reinitialises the prng when it is used after a fork.
- geofft 11y agoYeah, I'm asking a different question than the one that the post alludes to. I need to know from library code when I am on the `fork() == 0` side of a fork -- not just when I'm on a different side than I was previously on. (I'm writing a self-pipe signal handler, not a PRNG.) I don't think there's any way to answer my question without a syscall -- even the most naive approach uses getpid(). The post's solution works for my problem, but it uses a syscall. For background, see https://www.redhat.com/archives/libvir-list/2008-August/msg00303.html https://www.redhat.com/archives/libvir-list/2008-August/msg0... Syscalls ought to be pretty fast: without benchmarking, I don't think I'd assume that the cost of a syscall like getpid() is going to be slower than the cost of a copy-on-write fault for a MAP_PRIVATE page, since they both require kernel entry. Especially on systems where there's a syscall instruction instead of going through the full exception path, syscall-and-read-structure sounds faster than exception-and-remap-page.
- geocar 11y agoExcept you don't have a fault each check: You only have a fault if a fork has occurred. Using getpid/gettid (or the keyring trick) you are doing a syscall for every check.