1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// !> 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;
}