melisgl
melisgl

Reputation: 308

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 thread (on linux primarily, but windows, darwin are also of interest)?

Upvotes: 3

Views: 379

Answers (2)

MarkR
MarkR

Reputation: 63538

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.

Upvotes: 2

Rosh Oxymoron
Rosh Oxymoron

Reputation: 21055

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().

Upvotes: 2

Related Questions