开发者

checking whether fork() is safe

fork()'s behaviour is undefined if there are multiple threads in the process. How can I check that there is only a single th开发者_运维百科read (on linux primarily, but windows, darwin are also of interest)?


Under Linux, fork()'s behaviour is not undefined in a multithreaded process, but it does things which aren't normally very helpful.

Or rather, if you fork() and don't immediately call exec(), you risk a leak of unspecified resources, possibly including locks which could cause deadlock.

It's certainly possible to ask Linux (via procfs) how many threads there are in the current thread group. If the answer is one, that means the process is single-threaded.


It's not possible to do this. With pthreads you can use the pthread_is_multithreaded_np() function, but it would make your fork() code dependant on pthreads, and it doesn't work on all platforms. And there's no way to make the check regardless of the threading library.

If this is an application, just don't use threads and fork at the same time. If you are making a threaded program, never call fork() (with the exception of fork/execv combos).

If this is a library, either don't use fork() in it, or require that the library is never used with threaded applications.

Alternatively for an application, you can try to use pthread_atfork(...) to make it sure that it will be safe to call fork().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜