Inter process communication

Friday, May 26, 2006

Fork

User processes can in turn create children (for multitasking, perhaps) using the fork() function.


fork() creates a child that is duplicate of the parent process. All statements after the fork() function call are executed both in the parent as well as the child process. Any statements before the fork() would be executed only once.


In the following program, To the parent process fork() returns the PID of the child process or -1 in case of errors. In the child process the value of PID will always be 0.

main(){

int pid;
printf(“Before\n”);
pid = fork();
printf(“After\n”);
}

Output:

Before
After
After

main(){
fork();
fork();
printf(“Hello\n”);
}

Output:

Hello
Hello
Hello
Hello

Simply put, for n calls of fork(), there would be 2^n process’.

Note: Normally after a fork(), the time slice is given to the child process.

0 Comments:

Post a Comment

<< Home