Subject: Re: cygwin.dll src question: fork()
From: [email-masked] (Chris Faylor)

29 Oct 1997 15:45:26 -0800
Message-ID: <[email-masked]>
References: <[email-masked]>
Reply-To: [email-masked]
To: [email-masked]

In article <[email-masked]>,
Tim Newsham <[email-masked]> 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/	[email-masked]			"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
"[email-masked]" with one line of text: "help".