Question: / / redirect _ child.c: starts a child process which will print into a / / file instead of onto the screen. Uses dup 2
redirectchild.c: starts a child process which will print into a
file instead of onto the screen. Uses dup fork and wait
for this.
COMPLETE this code by filling in the TODO items
#include
#include
#include
#include
#include
int mainint argc, char argv
ifargc check for at least command line arg
printfusage: s
argv;
return ;
char outputfile argv; output file that child process will print into
char childargvwc"nums.txtNULL; child commandargumnets to execute; redirect output to file above
printfRemoving file s prior to run via a subshell
outputfile;
Create a string command and run it in a subshell; the 'system
command is a convenient way to forkexecwait a child
with blocking semantics
char command;
sprintfcommandrm f soutputfile;
systemcommand;
printfCreating a child to do s
childargv;
TODO: Spawn a child process
;
CHILD CODE
TODO: Conditional for child only
if
printfChild redirecting output to s then execing
outputfile;
TODO: Open outputfile for writing, same options as in switchstdout.c
int outfd
TODO: Copy outfd to standard output FD table entry
d;
TODO: Execute the command in childargv replacing this process
exec??;
printfexec seems to have failed...
; should not reach this
exit;
PARENT CODE
printfParent 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 exitreturn code of child process using wait macros
int retcode ;
printfChild complete, return code d
retcode;
else Child did not complete properly
printfChild terminated abnormally
;
exit;
printfShowing output of s via 'cat' command
outputfile;
Create another command to show the contents of outputfile; use
system to 'cat' the contents to the screen
sprintfcommand "cat s outputfile;
systemcommand;
return ;
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
