Question: / / redirect _ child.c: starts a child process which will print into a / / file instead of onto the screen. Uses dup 2

// redirect_child.c: starts a child process which will print into a
// file instead of onto the screen. Uses dup2(), fork(), and wait()
// for this.
//
// COMPLETE this code by filling in the TODO/??? items
#include
#include
#include
#include
#include
int main(int argc, char *argv[]){
if(argc <2){// check for at least 1 command line arg
printf("usage: %s
", argv[0]);
return 1;
}
char *output_file = argv[1]; // output file that child process will print into
char *child_argv[]={"wc","nums.txt",NULL}; // child command/argumnets to execute; redirect output to file above
printf("Removing file '%s' prior to run via a subshell
",
output_file);
// Create a string command and run it in a subshell; the 'system()'
// command is a convenient way to fork()+exec()+wait() a child
// with blocking semantics
char command[128];
sprintf(command,"rm -f %s",output_file);
system(command);
printf("Creating a child to do '%s'
", child_argv[0]);
// TODO: Spawn a child process
???=???;
// CHILD CODE
// TODO: Conditional for child only
if(???){
printf("Child redirecting output to '%s', then exec()'ing
",
output_file);
// TODO: Open output_file for writing, same options as in switch_stdout.c
int out_fd =???
// TODO: Copy out_fd to standard output FD table entry
d???(???);
// TODO: Execute the command in child_argv[] replacing this process
exec??(???);
printf("exec() seems to have failed...
"); // should not reach this
exit(1);
}
// PARENT CODE
printf("Parent waiting for child to complete
");
int status; // used to check return code of child
// TODO: Block until child is finished and check the output
????(???);
// TODO: check if the child exited properly using wait macros
if(???){
// TODO: extract exit/return code of child process using wait macros
int retcode =???;
printf("Child complete, return code %d
",retcode);
}
else{// Child did not complete properly
printf("Child terminated abnormally
");
exit(1);
}
printf("Showing output of '%s' via 'cat' command
",
output_file);
// Create another command to show the contents of output_file; use
// system() to 'cat' the contents to the screen
sprintf(command, "cat %s", output_file);
system(command);
return 0;
}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!