Both are wrong and invoke undefined behavior. You should be calling _exit(0) because it doesn't perform any cleanup in the child, it just ends the process. Since vfork() shares process memory between parent and child, letting the child perform process cleanup is a Bad Thing™.
Technically, the way you're using vfork() is undefined regardless of your exit strategy, as allowed actions in the child are severely limited:
(From POSIX.1) The vfork() function has the same effect as fork(2), 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(2) or one of the
exec(3) family of functions.
In other words, both the printf() call and modifying k in the child are not allowed. I'd suggest you forget that vfork() exists and simply use fork().
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,483
Solved Threads: 1,407
Skill Endorsements: 54
Last printf statement should not execute because child has returned to kernel using _exit(0); flushing all open streams and closing any open file descriptor.
IIRC, most versions of vfork() copy file descriptors, so closing them in the child is safe. However, I'm not 100% sure, so once again I'll recommend using fork() instead of vfork(). The potential performance benefits aren't worth the risk.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,483
Solved Threads: 1,407
Skill Endorsements: 54
Question Answered as of 1 Year Ago by
Narue