In: Computer Science
Write a C program which fork the process and have the child
execute a process.You have to implement void forkexec(char**
argv).This takes in an array of strings representing arguments.The
first argument is the filename of an executable (which will be
given as a "./a").The remaining terms would be arguments for said
executable.The array is null terminated and you need to fork your
process.The child needs to call exec/execvp to execute the
specified file with the specified arguments. Also have the parent
wait on the child. Assume that the first argument of argv is the
file name of the executable and argv is null terminated.
The program demostrates the use of fork() to create a child tread and inside the child thread we will execute a program. The parent process will wait until the child executes using the wait funtion available. The child program will print output when the control of execution reaches there.
Child program - sample.c
#include<stdio.h>
#include<unistd.h>
int main()
{
# This program is used to create the executable for testing the child process creation
int i;
printf("I am in child process called by execvp() ");
printf("\n");
return 0;
}
Main program - fork.c
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
void forkexec(char** argv)
{
pid_t childPid;
childPid = fork();
if(childPid == 0) // fork succeeded
{
// We are in child process
execvp(argv[0],argv);
exit(0);
}
else // Main (parent) process after fork succeeds
{
int returnStatus;
// wait for child to terminate
waitpid(childPid, &returnStatus, 0);
printf("The parent process is terminating.");
}
}
int main()
{
char *args[]={"./sample", NULL};
// Call the api for creating the process
forkexec(args);
return 0;
}
Output