// !> Redirection example [fv]
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <wait.h>
#include <stdio.h>
#include <assert.h>
// Implementing: sort < lines.txt > new_sorted_line.txt
int main(int argc, char **argv) {
pid_t sort_child = fork();
if (sort_child == 0) { // in the child
// first, close stdin, which makes file descriptor (fd) 0 available
close(0);
// now open lines.txt, claiming fd 0
int fd = open("lines.txt", O_RDONLY);
assert(fd == 0);
// now, close stdout, which makes fd 1 available
close(1);
// open new_sorted_lines.txt for writing, creating, truncating - claiming
// fd 1
int fd2 = open("new_sorted_lines.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
assert(fd2 == 1);
printf("This will be the first line of new_sorted_lines.txt\n");
execlp("sort", "sort", NULL);
// we should never get here
perror("Exec failed");
return 1;
// otherwise error and exit
}
printf("Parent can still stdout, only the child's stdout is redirected\n");
wait(NULL);
return 0;
}