Returning from main
is equivalent to calling exit
, which does a bunch of cleanup operations (such as flushing open FILE
objects and running atexit
procedures) and then calls _exit
, which is the system call that actually terminates a process. So when you call _exit
directly, you skip all of those cleanup operations.
You are using vfork
. It is incorrect (formally, it "provokes undefined behavior") to do anything on the child side of a vfork
except call _exit
or execve
. Returning from main
counts as doing something else (namely, calling exit
). It is not at all surprising, therefore, that your program crashes.
EDIT: As far as the relevant specifications are concerned, modifying the variables g_a
and l_b
on the child side of the vfork
is also forbidden, in the same dire terms ("undefined behavior" in the strong sense, i.e. "allowed to cause your program to crash"). However, in all extant implementations I am aware of, catastrophe only strikes if the child does anything to cause memory (including stack frames) to be allocated or deallocated. Modifying variables that were allocated by the parent, but visible to the child (whether local or global) is unpredictable in a much more bounded manner:
- If
vfork
is just another name for fork
, nothing the child does will be visible in the parent;
- But if
vfork
has its special behavior of delaying allocation of the new address space until execve
, then modifications by the child to variables resident in memory will be visible in the parent after the parent resumes execution. (Variables resident in registers may or may not get reset when the kernel restores the parent's execution context, depending on how full a context switch that does.)
And, if you know your OS is type 2, you can get away with using this to your advantage, e.g. to pass errno
back to the parent after execve
fails, which is significantly harder with plain fork
(because the exit status is too narrow). It is, however, something you are getting away with rather than something you are entitled to do; in particular it is a source of future portability headaches.