Assignment 2: Process Creation and Execution with
fork(), execvp(), and wait() System Calls
Objective:
The goal of this lab assignment is to explore process creation in Unix-
like operating systems using the system calls fork(), execvp(),
and wait(). This program demonstrates the interaction between a
parent and a child process, where the parent creates a child process
that executes a specified command.
1. fork() : fork is used to create new process. It returns to the child
process. A positive value (child’s pid) to the parent process and a
negative value if the fork failed.
2. execvp() : a system call used to execute a program by replacing the
current process image with a new process image. It is part of the exec
family of functions and is declared in the <unistd.h> header file.
3. wait() : This causes the parent process to block until the child
process terminates. The argument “NULL” means we don’t care
about the exit states of the child. For wait() we need to include
<sys/wait.h> header file.
Program:
#include<stdio.h>
#include<unistd.h>
#include<sys/wait.h>
#include<stdlib.h>
int main(int argc, char *argv[])
{
if(argc<2)
{
printf("Usage %s<command>[argument]in",argv[0]);
return 1;
}
int pid=fork();
if(pid<0)
{
printf("fork failed");
return 1;
}
if(pid ==0)
{
printf("Hello from child process=%d\n", getpid());
sleep(2);
execvp(argv[1],&argv[1]);
perror("execvp failed");
sleep(2);
exit(1);
printf("\nChild process completed");
}
else
{
printf("\nHello from child process=%d", getpid());
printf("\nWaiting for child process to complete");
wait(NULL);
printf("\nChild process is completed");
}
}
Output: