Jagdish
Jagdish

Reputation: 1922

Need clarification regarding vfork use

I want to run the child process earlier than the parent process. I just want to use execv call from the child process, So i am using vfork instead of fork.

But suppose execv fails and returns, i want to return non-zero value from the function in which i am calling vfork.

something like this,

int start_test()
{
  int err = 0;
  pid_t pid;
  pid = vfork();
  if(pid == 0) {
   execv(APP, ARGS);
   err = -1;
   _exit(1);
} else if(pid > 0) {
  //Do something else 
}
return err;
}

Is above code is proper, Or i should use some other mechanism to run child earlier than parent?

On some links, I have read that, We should not modify any parent resource in child process created through vfork(I am modifying err variable).

Upvotes: 2

Views: 596

Answers (2)

Dummy00001
Dummy00001

Reputation: 17460

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.

Upvotes: 2

Falko Büchner
Falko Büchner

Reputation: 126

Yes. You should not modify the variable err. Use waitpid in the parent process to check the exit code of the child process. Also check the return value from execv and the errno variable(see man execv), to determine why your execv fails.

Upvotes: 0

Related Questions