3

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)?

melisgl
  • 308
  • 2
  • 13
  • Wait. Why is this not a real question? Was there an edit that I missed? (Don't see an edit history though?) – Matti Virkkunen Dec 06 '10 at 17:01
  • @Matti Virkkunen: The originally posted question had no body (just `enter code here`) and a completely different title. – eldarerathis Dec 06 '10 at 17:01
  • @Matti: It was `insert code here`, but has been edited since -- edits within x minutes seemingly aren't recorded. I for one upvote and vote to reopen. –  Dec 06 '10 at 17:02
  • Yes, there was an edit. The original question just said `enter code here`, and the title was just "checking whether `fork()` threads" or something equally vague. – cHao Dec 06 '10 at 17:02
  • Ah. Figures. I guess it could be reopened now, though. – Matti Virkkunen Dec 06 '10 at 17:03
  • My downvote is locked unless the question is edited... I'll remove my downvote when possible... – GendoIkari Dec 06 '10 at 17:06
  • 1
    For reference, Windows doesn't have a `fork()` system call. – cHao Dec 06 '10 at 17:09
  • 1
    I am pretty sure fork() *is* defined for multiple threads. What is your evidence that it is not? – Zan Lynx Dec 06 '10 at 18:17

2 Answers2

2

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

Rosh Oxymoron
  • 20,355
  • 6
  • 41
  • 43
2

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.

MarkR
  • 62,604
  • 14
  • 116
  • 151
  • Yes, that's what I ended up doing (the procfs thing). We'll see what darwin has up its sleeve. – melisgl Dec 07 '10 at 13:45
  • You really have to hope that, after you've determined that there is exactly one thread in the process, nobody has a signal handler which starts a new one before you fork. That seems unlikely, at least. – MarkR Dec 08 '10 at 09:30