Path: csiph.com!news.swapon.de!aioe.org!.POSTED!not-for-mail From: Kaz Kylheku Newsgroups: comp.programming Subject: Re: Fork from a pthread Date: Mon, 24 Aug 2015 04:47:44 +0000 (UTC) Organization: Aioe.org NNTP Server Lines: 50 Message-ID: <20150823213807.832@kylheku.com> References: <4fc33328-cb7f-496f-a171-18702b9c2787@googlegroups.com> NNTP-Posting-Host: OGJi3KNpFOhM58UHZwXj0w.user.speranza.aioe.org X-Complaints-To: abuse@aioe.org User-Agent: slrn/pre1.0.0-18 (Linux) X-Notice: Filtered by postfilter v. 0.8.2 Xref: csiph.com comp.programming:5652 On 2015-08-23, moore_chestnut@yahoo.ie wrote: > Hello > > Posted this in C group and they mentioned POSIX experts would be in this group. > > In C on *nix environment, can you fork a process from within a thread? Yes; in fact, if you don't have a thread, you cannot call any function at all. > Is the thread invoking the fork replicated only or everything in the process? POSIX fork creates a new child in which execution continues in a copy of the thread which called fork. All the other threads are there, in terms of their user-space data structures; however they are effectively "dead". In the copied process, it looks as if all the threads suddenly disappeared. And that means, no matter what they were doing at the time of the fork call: like half-way through updating some shared structure, or half-way trhough unlocking a mutex, etc. > What about heap memory - not directly allocated by the thread but can be > referenced by it. Memory is all classic fork. > man page for fork suggests you can but when i try, the fork seems to just > hang. Forking and multiple threads do not mix very well. If a process with multiple threads calls fork, the only reasonable thing it can do is to exec a new image. There is a half-baked mechanism (like almost anything thread-related in POSIX) in the form of a function called pthread_atfork. With this, you may be able to write multi-threaded modules that can continue working in a forked process. With pthread_atfork, you can register fork handlers in the form of triplets of functions: a pre-fork handler, and two post-fork handlers (one for the parent and one for the child). When fork is called, then all of the pre-fork handlers are called first. Then the fork takes place. Then the post-fork handlers are called in the parent, and in the child. With these handlers, you can try to do something like acquire a mutex before the fork, and then reinitialize it in the parent and child process. This way none of the threads which disappear at fork time can possibly be holding that mutex. > What may cause this? Without seeing your forking code, impossible to tell.