Ahan Hsieh 謝武漢 wrote:
>    After system call vfork() is called, the parent is suspended and
>    cannot continue executing until the child exits or calls exec(),
>    the system call used to start a new application.
>    The child, directly after returning from vfork(),
>    is  running on the parent's stack and is using the parent's memory and
>    data.
>    This  means  the child can corrupt the data structures or the stack in
>    the parent, resulting in failure.
>    How can I avoid the problem? Is there any solution?

Because of the shared memory, there's very little you can safely
do in a vfork child process.  It is meant only for calling exec().

The Single Unix standard says what is safe in a vfork child:

    http://www.opengroup.org/onlinepubs/000095399/functions/vfork.html

    The vfork() function shall be equivalent to fork(), except that
    the behavior is undefined if the process created by vfork() either
    modifies any data other than a variable of type pid_t used to
    store the return value from vfork(), or returns from the function
    in which vfork() was called, or calls any other function before
    successfully calling _exit() or one of the exec family of
    functions.

The solution is to call exec() or _exit() in the child, immediately
after the call to vfork(), in a simple way which doesn't corrupt the
stack.

(Always use _exit(), not exit()).

For example:

     pid_t pid = vfork ();
     if (pid == 0) {
         /* Code for child.  Be careful not to corrupt parent's memory,
            by only doing things which are safe in a vfork child. */
         execv (child_program_name, child_args);
         /* If the execv call fails, exit with an error. */
         _exit (254);
     }
     /* Code for parent.  Everything is safe after here. */

With old compilers, that can't corrupt the stack.  Modern optimising
compilers could corrupt the stack in principle just from the function
call to execv(), but GCC detects when a function calls vfork(), and
avoids optimising the function too much in that case, to make sure it
won't corrupt the parents stack.

On uClinux (not other OSes), there are other things you can safely do
in a vfork child.  Most system calls are ok, like setsid(),
setreuid(), close(), dup2(), Avoid libc calls - especially, don't call
malloc() or free().

-- Jamie
_______________________________________________
uClinux-dev mailing list
uClinux-dev@uclinux.org
http://mailman.uclinux.org/mailman/listinfo/uclinux-dev
This message was resent by uclinux-dev@uclinux.org
To unsubscribe see:
http://mailman.uclinux.org/mailman/options/uclinux-dev

Reply via email to