EmbLogic's Blog

Process Duplication using fork

Process Duplication using system call fork
==============================
- A new process is created using fork().
- fork() is a system call.
- fork duplicates the current process.
- It creates a new entry in the process table with many of same

attributes as current process.
- The new process (known as child process) is almost identical to

original process (known as parent process).
- PPID (Parent Process Identification) of new process is PID of

original process.
- PID (Process Identification) of new process is lowest PID

available after the PID of original process .Mostly it is 1 greater

than the original process(If available).
- Prototype of fork :-
pid_t fork(void);
- Function fork() is declared in header:
#include<unistd.h>
- It has a return type pid_t .
- System type pid_t is declared in header :
#include<sys/types.h>
- The Process counter of new process starts from fork() statement.
- So, fork() is executed twice.
- When fork() is executed by parent, it returns PID of child

process on success.
- When fork() is executed by child, it returns 0 for success.
- If fork fails, it returns -1.
- Falure may be due to :-
* Limit on the number of child processes that a parent may

have (CHILD_MAX), in which errno will be set to “EAGAIN”

* If process table or virtual memory is filled (not enough

space), errno variable will be set to “ENOMEM”.
- The return value of fork() can be used to determine whether child

or parent is executing.
- For eg. :-
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
int main()
{
pid_t fret;
printf(“Only parent execute\n”);
fret = fork();//Fork statement
printf(“Both parent and child execute this statement.\n”);
switch(fork)
{
case -1 :
perror(“fork”);
exit(EXIT_FAILURE);
break;
case 0 :
printf(“Child executing\n”);
break;
default :
printf(“Parent executing\n”);
break;
}
return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>