Here is the full code:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>
int main(int argc, char *argv[]) {
char *command, *infile, *outfile;
int wstatus;
command = argv[1];
infile = argv[2];
outfile = argv[3];
if (fork()) {
wait(&wstatus);
printf("Exit status: %d\n", WEXITSTATUS(wstatus));
}
else {
close(0);
open(infile, O_RDONLY);
close(1);
open(outfile, O_CREAT|O_TRUNC|O_WRONLY, 0644);
execlp(command, command, NULL);
}
return 0;
}
This code should fork and exec a command with both stdin and stdout redirection, then wait for it to terminate and printf WEXITSTATUS(wstatus)
received. e.g. ./allredir hexdump out_of_ls dump_file
.
So, I understand everything before fork()
. But I have the following questions:
- As far as I understand,
fork()
clones the process, however I do not understand how it executes the command, becauseexeclp
should do that and code never reaches that part. - I do not get how
execlp
works. Why do we send a command to it twice (execlp(command, command, NULL);
)? - How does
execlp
know where to redirect the output if we do not passoutfile
nowhere. - Why do we even need an
infile
if the command is already passed as the other argument?
Thank you for your answers in advance.