Linux Format

It’s all redirection!

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.

You’re reading a preview, subscribe to read more.

More from Linux Format

Linux Format1 min read
Ultimate Desktop Upgrade!
LXF316 will be on sale Tuesday 28th May 2024 Word processors that can help craft that novel you’ve always been talking about and organise large projects. Revive the old roleplaying system for a digital age as we recreate our own play-by-mail gaming
Linux Format4 min read
Linux
The #1 open source mag Future Publishing Limited, Quay House, The Ambury, Bath, BA1 1UA Email contact@linuxformat.com EDITORIAL Editor-in-chief Neil Mohr Art editor Fraser McDermott Production editor Katharine Davies Group editor-in-chief Graham Bar
Linux Format2 min read
Platform Support And Editions
Kali has a huge variety of install options, and these include images for ARM-based computers and pre-made virtual K machine images for most of the popular virtualisers. It’s even possible to install a version of Kali on to an Android-powered device.

Related Books & Audiobooks