Header Ads Widget

Process Generation

Process creation is achieved through the fork() system call. The newly created process is called the child process and the process that initiated it (or the process when execution is started) is called the parent process. After the fork() system call, now we have two processes - parent and child processes. How to differentiate them? Very simple, it is through their return values.

After creation of the child process, let us see the fork() system call details.

#include <sys/types.h>

#include <unistd.h>

pid_t fork(void);


Creates the child process. After this call, there are two processes, the existing one is called the parent process and the newly created one is called the child process.

The fork() system call returns either of the three values −

  • Negative value to indicate an error, i.e., unsuccessful in creating the child process.
  • Returns a zero for child process.
  • Returns a positive value for the parent process. This value is the process ID of the newly created child process.

Let us consider a simple program.

File name: basicfork.c

#include <stdio.h>

#include <sys/types.h>

#include <unistd.h>

 

int main() {

   fork();

   printf("Called fork() system call\n");

   return 0;

}

Execution/Output

Called fork() system call

Called fork() system call

Note − Usually after fork() call, the child process and the parent process would perform different tasks. If the same task needs to be run, then for each fork() call it would run 2 power n times, where n is the number of times fork() is invoked.

In the above case, fork() is called once, hence the output is printed twice (2 power 1). If fork() is called, say 3 times, then the output would be printed 8 times (2 power 3). If it is called 5 times, then it prints 32 times and so on and so forth.

Post a Comment

0 Comments