This is the mail archive of the cygwin@sourceware.cygnus.com mailing list for the Cygwin project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: cygwin.dll src question: fork()


In article <m0xQToy-0010xOC@malasada.lava.net>,
Tim Newsham <newsham@lava.net> wrote:
>   Question: Why is a setjmp/longjmp pair used in __fork():
>
>        static int
>        __fork ()
>        {
>          jmp_buf b;
>          int r;
>        
>          if ((r = setjmp (b)) != 0)
>            {
>              r = r == -2 ? -1 : r == -1 ? 0 : r;
>              return r;
>            }
>        
>          r = cygwin_fork_helper1 (u->data_start, u->data_end,
>                                         u->bss_start, u->bss_end);
>        
>          /* Must convert result to get it through setjmp ok.  */
>          longjmp (b, r == -1 ? -2 : r == 0 ? -1 : r);
>        }
>
>At the time when cygwin_fork_helper1() returns isn't the
>child's state already a copy of the parent's state?

No, actually, it isn't.  The setjmp and longjmp are used to move the
current execution point into the appropriate point in the cygwin_fork_helper1
function to emulate a true UNIX fork().

What happens is that to emulate a fork, the parent process starts the
child in a suspended state using CreateProcess.  The child is merely
another invocation of the parent program.  While the child is suspended,
the parent fills in all of the cygwin specific information for the
child, setting a flag to indicate that the child is forked.

The parent starts the child and then "sleeps".  The child goes through
part of the standard cygwin initialization, notices that it is forked,
extends the stack to hopefully insure that the stack is large enough to
duplicate the parent, and longjmps to the child portion of the
cygwin_fork_helper1 routine.  There it wakes up the parent and sleeps
itself.

At that point the parent fills in the child's stack and heap and wakes
up the child who now, theoretically, has a carbon copy of the parent's
environment, just like a real UNIX fork (but with a lot more overhead).

I think that's it in a nutshell.  It is obviously a pretty complicated
process owing to the fact that there is no real analog to fork() in the
standard Win32 API.
-- 
http://www.bbc.com/	cgf@bbc.com			"Strange how unreal
VMS=>UNIX Solutions	Boston Business Computing	 the real can be."
-
For help on using this list (especially unsubscribing), send a message to
"gnu-win32-request@cygnus.com" with one line of text: "help".


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]