When vfork() can replace fork() (Was: Some questions about linux kernel. )

From: Rask Ingemann Lambertsen (rask-linux@kampsax.k-net.dk)
Date: Mon Mar 20 2000 - 18:52:07 EST


Den 16-Mar-00 11:55:36 skrev Brandon S. Allbery KF8NH fĝlgende om "Re: Some questions about linux kernel. ":
> In message <3141.109T950T10773650rask-linux@kampsax.k-net.dk>, "Rask
> Ingemann L
> ambertsen" writes:
> +-----
>| vfork() can replace fork() in pretty much any variety of fork()/exec()
>| or fork()/wait(). This covers the wast majority of uses of fork(). The
> +--->8

> ...as long as you don't need to make any function calls with side effects
> and the exec() ALWAYS succeeds; otherwise the child trashes the parent.

> vfork() is a bug.

   You have to be careful how the child exits in case of exec*() failure,
whether you use fork() or vfork(). Here is an example where it goes wrong
using fork():

[root@vissevasse /root]# cat forkmess.c
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <stdio.h>

int main (int argc, char *argv[])
{
        int status;

        fputs ("Output from parent: ", stdout);

        switch (fork ())
        {
                case 0:
                execl ("/dev/null", "null");
                return (EXIT_FAILURE);
                break;

                case -1:
                putchar ('\n');
                perror ("fork()");
                return (EXIT_FAILURE);
                break;

                default:
                wait (&status);
                return (EXIT_SUCCESS);
                break;
        }
}
[root@vissevasse /root]# gcc forkmess.c -o forkmess
[root@vissevasse /root]# ./forkmess
Output from parent: Output from parent: [root@vissevasse /root]#

   The detail here is that the child must use _exit() instead of return()
or exit() if exec*() fails.

   AFAIK there is no problem in using open()/dup()/dup2()/close() in the
child between vfork() and exec(). That's enough to cover the most common
uses of fork()/exec().

Regards,

/ŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻTŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻ\
| Rask Ingemann Lambertsen | E-mail: mailto:rask@kampsax.dtu.dk |
| Please do NOT Cc: to me or the | WWW: http://www.gbar.dtu.dk/~c948374/ |
| mailing list. I am on the list.| "ThrustMe" on XPilot, ARCnet and IRC |
| 3 kinds of people: Those who can count & those who can't. |

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



This archive was generated by hypermail 2b29 : Thu Mar 23 2000 - 21:00:32 EST