Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vfork() system call

I read that the new process created using vfork() system call executes as a thread in the parent's address space and until the child thread doesnot calls exit() or exec() system call, the parent is blocked. So I wrote a program using vfork() system call

#include <stdio.h>  
#include <unistd.h>

int main()  
 {  
      pid_t pid;  
      printf("Parent\n");  
      pid = vfork();  
      if(pid==0)  
      {  
          printf("Child\n");  
      }  
      return 0;  
  }

I got the output as follows:

 Parent  
 Child  
 Parent  
 Child  
 Parent  
 Child  
 ....  
 ....  
 ....

I was assuming that the return statement must be calling the exit() system call internally so I was expecting the output as only

Parent  
Child

Can somebody explain me why actually it is not stopping and continuously printing for infinite loop.

like image 735
pradeepchhetri Avatar asked May 20 '11 12:05

pradeepchhetri


People also ask

What is vfork () in Linux?

LINUX DESCRIPTION vfork() is a special case of clone(2). It is used to create new processes without copying the page tables of the parent process. It may be useful in performance sensitive applications where a child will be created which then immediately issues an execve().

What is fork () vfork () and exec ()?

Overview. System calls provide an interface to the services made available by an operating system. The system calls fork(), vfork(), exec(), and clone() are all used to create and manipulate processes.

What happens when a running process execute a vfork () call?

When a vfork system call is issued, the parent process will be suspended until the child process has either completed execution or been replaced with a new executable image via one of the "exec" family of system calls.

What is Vfork in C?

The vfork() function creates a new process. The vfork() function has the same effect as fork(), except that the behavior is undefined, if the process created by vfork() attempts to call any other C/370 function before calling either exec() or _exit().


1 Answers

You should read the man page for vfork very carefully:

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.

(above is from the POSIX part of the man page, so applies (potentially) to other environments than Linux).

You're calling printf and returning from the child, so the behavior of your program is undefined.

like image 184
Mat Avatar answered Sep 22 '22 15:09

Mat