lkml.org 
[lkml]   [2004]   [Aug]   [13]   [last100]   RSS Feed
Views: [wrap][no wrap]   [headers]  [forward] 
 
Messages in this thread
/
Date
From
SubjectRe: 2.6.x Fork Problem?
On Fri, 13 Aug 2004, Frank van Maarseveen wrote:

> On Thu, Aug 12, 2004 at 09:26:27AM -0500, Jesse Pollard wrote:
> > On Wednesday 11 August 2004 19:01, Torin Ford wrote:
> > >
> > > pid = fork();
> > > switch (pid)
> > > {
> > > case -1:
> > > blah; /* big trouble */
> > > break;
> > > case 0: /* Child */
> > > exit(1);
> > > break;
> > > default: /* Parent */
> > > pid2 = waitpid(pid, &status, 0);
> > > if (pid2 == -1)
> > > {
> > > blah; /* check out errno */
> > > }
> > > }
> >
> > Yup - the parent process executed waitpid before the child process finished
> > the setup. This can happen in a multi-cpu environment or even a single, if
> > the scheduler puts the parent process higher than the child in the queue.
>
> ugh! I can follow the rationale for SMP.
>
> But wouldn't this kind of behavior actually break most real world programs?
>
> --
> Frank

When fork() returns with a pid. The pid is valid. It cannot
be that the child doesn't exist yet. This would, as you said,
break everything. What seems to happening is the child calls
exit() before the parent gets the CPU. The child should wait
in exit() until somebody claims its status.

There has never been any guarantee that the child gets the CPU
sooner than the parent. If the parent and child need to synchronize
things, there are lots of ways to do it.

In the above code there is something missing. in the code shown,
the child __will__ wait in exit() until somebody claims its status.
However, the child probably did a setsid(), becoming a process-leader
or the parent set up a SIGCHLD handler before the fork. In these
cases, the exit() will quickly exit because somebody will claim
the exit status.

So, by the time the parent gets the CPU, the child is long gone.
The solution is to use the default SIGCHLD handler if the parent
expects to get the child's status and for the child to not execute
setsid(), which will allow init to reap its status.

Cheers,
Dick Johnson
Penguin : Linux version 2.4.26 on an i686 machine (5570.56 BogoMips).
Note 96.31% of all statistics are fiction.


-
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@vger.kernel.org
More majordomo info at http://vger.kernel.org/majordomo-info.html
Please read the FAQ at http://www.tux.org/lkml/

\
 
 \ /
  Last update: 2005-03-22 14:05    [W:0.060 / U:0.504 seconds]
©2003-2020 Jasper Spaans|hosted at Digital Ocean and TransIP|Read the blog|Advertise on this site