Program that will create a new child process using fork() system call.


The fork() System Call:
System call fork() is used to create processes. It takes no arguments and returns a process ID. The purpose of fork() is to create a new process, which becomes the child process of the caller. After a new child process is created, both processes will execute the next instruction following the fork() system call. Therefore, we have to distinguish the parent from the child. This can be done by testing the returned value of fork():
  • If fork() returns a negative value, the creation of a child process was unsuccessful.
  • fork() returns a zero to the newly created child process.
  • fork() returns a positive value, the process ID of the child process, to the parent. The returned process ID is of type pid_t defined in sys/types.h. Normally, the process ID is an integer. Moreover, a process can use function getpid() to retrieve the process ID assigned to this process.
Therefore, after the system call to fork(), a simple test can tell which process is the child. Please note that Unix will make an exact copy of the parent's address space and give it to the child. Therefore, the parent and child processes have separate address spaces.
Code:
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<errno.h>
int main(int argc, char *argv[])
{
pid_t pid;
pid=fork();
if (pid == 0) {
printf("This is the child process. My pid is %d and my parent's id is %d.\n", getpid(), getppid());
}
else {
   printf("This is the parent process. My pid is %d and my parent's id is %d.\n", getpid(), pid);
}
return 0;
}

Output:





















No comments:

How to crack Aptitude Question In GATE and many Competitive Examination

As you know the aptitude in the competitive examination is quite for more challenging to clear it. But believe me it is the easy stuff t...