Please complete the following code for challenge.c in C according to the instructions in the comments. Further instructions are below in INSTRUCTIONS.txt
challenge.c
#include "challenge.h"
// goal: fork the process and have the child execute a process
// param argv: the argument vector for the process to be executed
// assumptions:
// the first argument of argv is the file name of the executable
// argv is null terminated
//
// TODO: complete the function
// fork
// exec (child), probably most convenient to use execvp
// have the parent wait on the child
void fork_exec(char** argv)
{
}
---
INSTRUCTIONS.TXT
You have one function to implement: void fork_exec(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 relative filepath, such as "./a")
The remaining terms would be arguments for said executable.
The array is null terminated
You need to fork your process.
The child needs to call exec (rather, a variant thereof) to execute the specified file with the specified arguments.
Hint: I recommend using execv for the exec-ing part
execve is under manual section 2
other exec variants are under manual section 3
Please find the requested program below. Also including the screenshot of code to understand the indentation.
Please provide your feedback
Thanks and Happy learning!
#include <stdio.h>
#include <unistd.h>
void fork_exec(char** argv)
{
int childExitStatus;
pid_t pid = fork();
if (pid == -1)
{
printf("Failed to fork a new process.\n");
return;
}
if (pid == 0)
{
//In Child process
execvp(argv[0], argv);
}
else
{
//In parent process
//wait for the child to finish
wait(&childExitStatus);
}
}
int main(int argc, char** argv)
{
fork_exec(argv);
return 0;
}
Get Answers For Free
Most questions answered within 1 hours.