4 ms·
If you are in control of all the threads that an application is running, you can call fork() safely by making sure the threads are put in a safe state (no criti
by antirez 10y ago
If you are in control of all the threads that an application is running, you can call fork() safely by making sure the threads are put in a safe state (no critical locks retained) when the fork() call happens. Also note that many things that should normally be unsafe, like having running threads calling malloc() while another thread is forking, are actually safe in the real world using certain implementation of fork, since there are pre/post fork "hooks" in the malloc implementation in order to fix the state of the child.
So if you control very closely the libs you link with and what they do, as well as the threads you use yourself, it is possible to use fork() in a reliable way.
- deleted 10y ago[deleted]
- deleted 10y ago[deleted]
- tankenmate 10y agoglibc attempts this using the pthread_atfork() hook. it takes the global malloc (and possibly other) forks in the parent before forking, then both the parent and child release the lock before returning to the callee's code. obviously if you have locks in your own code then you may or may not need to hold these before calling fork() so that both parent and child can release them after the fork(). the apple way of just throwing its hands in the air and abort()ing sound either like giving up because the apple devs think it is too hard, or because they feel the need to impose their way in crippling code that uses fork() without calling exec() in my opinion if you are going to write a library that uses threads and is supposed to be thread safe then remember you need to handle the issue of fork(); don't be lazy, do the job properly, even if doing it right it is hard and ugly.
- evanj 10y agoYou are completely correct! The thing that surprised me is how difficult that can be. For example, on Mac OS X if you want to read the system proxy settings, you magically get threads added to your program that you can't control.