Write a shell
It’s all redirection!
LXF SHELL
Still not afraid of the depth of Linux systems, Ferenc Deak continues his daring journey to show us how to implement redirection in our own shell.
Part Two!
Don’t miss next issue, subscribe on page 16!
OUR EXPERT
Ferenc Deak is still not convinced that Malbolge wasn’t the right choice to create a Linux shell, but now there is no turning back. It’s C++.
n the debut chapter of this shell series, we successfully implemented the execution of I applications within our freshly minted shell, aptly named lxf-shell. As we embark on the next part of our adventure, our sights are firmly set on one particularly distinguished feature no shell should live without: the art of redirecting application output to destinations far more interesting than standard output.
Output redirection is a feature that allows you to control where the output of a command is sent. It enables you to capture or redirect the standard output and error streams generated by a command to a file or another destination, rather than displaying the output on the terminal.
Duplicated duplicate
Redirecting output programmatically takes a bit of work, but nothing we can’t handle. It basically boils down to the proper usage of the dup2 function (found in unistd.h). The dup2 command is a system call in Linux used for duplicating file descriptors. It enables you to create a copy of an existing file descriptor, associating it with a different file or device. The following example presents how to use it to redirect the standard output of an application:
This quick C code snippet opens a file named output.txt for writing, with the specified flags: O_WRONLY: The file should be opened for writing. O_CREAT: Creates the file if it does not exist. O_TRUNC: Truncates the file to zero length if it exists. S_IRUSR | S_IWUSR: These are file permissions, allowing both reading and writing for the file owner.
In case of errors, we just give up and leave the application. In the next step, we use the dup2() function to duplicate the file_descriptor and associate it with the standard output file descriptor (STDOUT_FILENO). As a result, any data written to STDOUT_FILENO (that is stdout, the standard output) is directed to the output.txt file. If the dup2() function fails, it returns -1, and this is handled ungraciously by just giving up and exiting again.
We close the original file descriptor to release the allocated system resources since we don’t need them any more; the file descriptor duplication ensures what goes to the standard output is also delivered to the file output.txt. Finally, the program prints the message Hello mon duplicate!\n using fprintf(), and since the standard output has been redirected, the message is saved in the output.txt file rather than being displayed on the terminal.