6
votes

Considering the below code :

int main()
{
  int pid;
  pid=vfork();
  if(pid==0)
     printf("child\n");
  else
     printf("parent\n");
  return 0;
  }

In case of vfork() the adress space used by parent process and child process is same, so single copy of variable pid should be there. Now i cant understand how this pid variable can have two values returned by vfork() i.e. zero for child and non zero for parent ?

In case of fork() the adress space also gets copied and there are two copy of pid variable in each child and parent, so I can understand in this case two different copies can have different values returned by fork() but can't understand in case of vfork() how pid have two values returned by vfork()?

1
That's lethal - you can exec() or _exit() in the vfork()'d child, but that's just about it. Pretty much anything else leads to undefined behaviour. Recommendation: don't use vfork(); indeed, I wouldn't even bother to learn how to use it safely. It's like gets(), a function that it is best to pretend doesn't exist.Jonathan Leffler
@JonathanLeffler: vfork() is quite useful for MMU-less systems.ninjalj
Yes sir, I agree with u we should not use it, but I was using vfork to solve one problem of creating process tree and communication between processes of different levels of tree, in that case vfork was useful taking some global variable. I'll keep ur advice.L.ppt
@L.ppt: ummm. no, that's a bad use of vfork(). Better use some real IPC (shared memory, sockets, pipes, ...), or, if you really really know what you are doing, threads.ninjalj
I'll translate R..'s comment: vfork() is useful for spawning processes from Java (where else can you find such large address space wastage?), and indeed Java 1.7 seems to have added support for vfork() and posix_spawn().ninjalj

1 Answers

6
votes

There aren't 2 copies. When you cal vfork the parent freezes while the child does its thing (until it calls _exit(2) or execve(2)). So at any single moment, there's only a single pid variable.

As a side note, what you are doing is unsafe. The standard spells it clearly:

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.

As a second side note, vfork has been removed from SUSv4 - there's really no point in using it.