Write the program to create a Child Process using system call fork().
Program Algorithm:
Step 1 : Declare the variable pid.
Step 2 : Get the pid value using system call fork().
Step 3 : If pid value is less than zero then print as “Fork failed”.
Step 4 : Else if pid value is equal to zero include the new process in the system‟s file using execlp system call.
Step 5 : Else if pid is greater than zero then it is the parent process and it waits till the child completes using the system call wait() Step 6 : Then print “Child complete”.
System Calls Used:
1. fork( ) Used to create new processes. The new process consists of a copy of the address space of the original process. The value of process id for the child process is zero, whereas the value of process id for the parent is an integer value greater than zero.
Syntax : fork( )
2.execlp( ) Used after the fork() system call by one of the two processes to replace the process‟ memory space with a new program. It loads a binary file into memory destroying the memory image of the program containing the execlp system call and starts its execution.The child process overlays its address space with the UNIX command /bin/ls using the execlp system call.
Syntax : execlp( )
3. wait( ) The parent waits for the child process to complete using the wait system call. The wait system call returns the process identifier of a terminated child so that the parent can tell which of its possibly many children has terminated.
Syntax: wait( NULL)
4. exit( ) A process terminates when it finishes executing its final statement and asks the operating system to delete it by using the exit system call. At that point, the process may return data (output) to its parent process (via the wait system call).
Syntax: exit(0)
Program Code:
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
void main(int argc,char *arg[])
{
int pid;
pid=fork();
if(pid<0)
{
printf("fork failed");
exit(1);
}
else if(pid==0)
{
execlp("whoami","ls",NULL);
exit(0);
}
else
{
printf("\n Process id is -%d\n",getpid());
wait(NULL);
exit(0);
}
}
Post A Comment:
0 comments: