Is above code is proper?
No. The err
variable is already in the child's memory, thus parent will not see its modification.
We should not modify any parent resource in child process created through vfork (I am modifying err variable).
The resource is outdated. Some *nix systems in the past tried to play tricks with the fork()
/exec()
pair, but generally those optimizations have largely backfired, resulting in unexpected, hard to reproduce problems. Which is why the vfork()
was removed from the recent versions of POSIX.
Generally you can make this assumptions about vfork()
on modern systems which support it: If the child does something unexpected by the OS, the child would be upgraded from vfork()
ed to normal fork()
ed one.
For example on Linux the only difference between fork()
and vfork()
is that in later case, more of the child's data are made into lazy COW data. The effect is that vfork()
is slightly faster than fork()
, but child is likely to sustain some extra performance penalty if it tries to access the yet-not-copied data, since they are yet to be duplicated from the parent. (Notice the subtle problem: parent can also modify the data. That would also trigger the COW and duplication of the data between parent and child processes.)
I just want to use execv
call from the child process, So i am using vfork
instead of fork
.
The handling should be equivalent regardless of the vfork()
vs fork()
: child should return with a special exit code, and parent should do the normal waitpid()
and check the exit status.
Otherwise, if you want to write a portable application, do not use the vfork()
: it is not part of the POSIX standard.
P.S. This article might be also of interest. If you still want to use the vfork()
, then read this scary official manpage.