File descriptors

Lab exercises for Feb 5th. Due Feb 6th

The goals for this assignment are:

  • Inspecting processes, pipes, and file descriptors

We will use the same repository as last week: Labs Repo.

1. File redirection

In the file, filesort.c, implement a program that runs the command sort < list.txt using the system calls: open, close, fork, execlp, and dup2.

$ cat list.txt
banana
apple
orange
kiwi
$ ./filesort
apple
banana
kiwi
orange
Sort complete

In the above example, filesort performs the following steps:

  • Creates a child process with fork

  • The child process does the following:

    • Opens the file "list.txt"

    • Maps the file descriptor for "list.txt" to standard input

    • Calls execlp with arguments that correspond to sort, e.g execlp("sort", "sort", (char*) NULL)

  • The parent process does the following:

    • Waits for the child to complete

Don’t forget to implement error handling. Check the return code of system calls and use perror to report errors if they occur.

2. Pipe

In the file, catsort.c, implement a program that runs the command cat list.txt | sort using the system calls: pipe, fork, execlp, and dup2.

$ cat list.txt
banana
apple
orange
kiwi
$ ./catsort
apple
banana
kiwi
orange
Cat complete
Sort complete

In the above example, catsort performs the following steps:

  • Creates a pipe

  • Creates two child processes with fork

  • Each child process does the following:

    • Uses dup2 to map one side of the pipe with either standard input or output.

    • Closes the ends of the pipe

    • Calls execlp with arguments that correspond to the command

  • The parent process does the following:

    • Closes the ends of its pipe

    • Waits for both children to complete

Don’t forget to implement error handling by checking the return code and printing the error with perror is the status of the system call is < 0.