GB
  
You are currently viewing the United Kingdom version of the site.
Would you like to switch to your local site?
13 MIN READ TIME

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.

Unlock this article and much more with
You can enjoy:
Enjoy this edition in full
Instant access to 600+ titles
Thousands of back issues
No contract or commitment
Try for 99p
SUBSCRIBE NOW
30 day trial, then just £9.99 / month. Cancel anytime. New subscribers only.


Learn more
Pocketmags Plus
Pocketmags Plus

This article is from...


View Issues
Linux Format
February 2024
VIEW IN STORE

Other Articles in this Issue


WELCOME
MEET THE TE AM
We’re all about taking back control this issue, implementing Pi-hole protection. What open source tools do you use to help bring control back to your life?
Corporate takeover
Who said history repeats itself? First there was
REGULARS AT A GLANCE
Google steps up arms race against ad blockers
EXTENSIONS
X.Org being phased out
For four decades, the X Window System has endured despite competition, but major OSes are bowing out.
Road map to GIMP 3
Latest version of GIMP finally has a release schedule.
ALL AI HYPE
My crystal ball is only slightly better than
ALL IN THE PIPE!
PipeWire 1.0 was released late November (see right),
PipeWire turns 1.0
The audio/video bus designed to replace PulseAudio, JACK and other systems has now reached version 1.0.
More Linux-first laptops
Linux come preinstalled on more and more machines.
Open firmware doing very well
100 million firmware updates supplied by the LVFS.
Distro watch
What’s behind the free software sofa?
NEW YEAR! NEW LIBRE!
Like every year, there will be two new
UPSTREAM FUNK
A recent data corrupting bug in the ext4
Kernel Watch
Jon Masters keeps up with all the latest happenings in the Linux kernel, so you don’t have to.
Answers
Got a burning question about open source or the kernel? Whatever your level, email it to answers@linuxformat.com
Mailserver
I think we’ve misplaced the PDP-1 in the
HotPicks
Recoll »Polybar »Curtail »Betterbird »Bleach» Bit FileZilla» JDownloader
LINUX FORMAT
The #1 open source mag Future Publishing Limited,
REVIEWS
Intel Core i5 14600K
No one calls Jacob Ridley mid-range!
EndeavourOS 11-2023
Nate Drake endeavours to discover all that is great about this Arch-based Linux distro, created by former Antergos developers.
SysLinuxOS 12.2
Nate Drake dives into SysLinuxOS to find whether its reputation as the dream OS for system administrators is well deserved.
OpenMandriva Lx 5.0
Nate Drake relives Mandriva Linux’s heyday with its programmer and community-developed successor. Plasma has never looked so good.
Ultramarine Linux 39
Nate Drake decides to take this Thai Fedora-based distro for a spin and finds it fast, simple and surprisingly customisable.
Steam Deck OLED
Management is overjoyed: “Take an old product and slap a new badge on for more money?” Tyler Colp likes his job too much to correct them.
ROUNDUP
File managers
Dolphin Krusader Midnight Commander Nemo Thunar
STAY SAFE ONLINE!
Eat unwanted online nasties by sending packets to the Pi-hole. David Rutland helps you protect your browsing data with the ultimate in a paranoid’s delight!
Pi USER
Coolest Projects 2024 remote and in person
Start your Raspberry Pis! The coolest digital creators competition is ready to open in 2024.
Ubuntu 23.10 for Pi
The ever dapper Les Pounder has been using Ubuntu since Dapper Drake and has been looking forward to sampling this Pi-based iteration.
Bambu Lab A1 Mini
Good things come in small packages is something Denise Bertacchi never says – now she’s eating her delicious words.
Build a Pi Pico electronic piano
Les Pounder is trying his best to make his mum proud by not taking apart an electronic piano!
Torrent your slice of Pi
Torrenting isn’t all about taking – Christian Cawley helps you use a Raspberry Pi to serve open source ISOs on the BitTorrent P2P network.
IN DEPTH
The rise and fall (and rise again) of Basic
We plot the symbolic milestones of the most basic of allpurpose code with the instruction of Mike Bedford.
Roll out the Rhino!
In an increasingly crowded marketplace, Nick Peers discovers why this new Ubuntu derivative might be a barrel of fun!
TUTORIALS
Total shell recall
Too busy running around shouting, “Get your ass to Mars,” Shashank Sharma thinks a strong shell history can be a real life saver.
Build your own home CCTV system
Nick Peers reveals how to bypass expensive (and insecure) cloud security systems to create your own using a variety of cameras.
Emulate an analogue computer digitally
Today, computers are nearly always digital, but analogue computers also had their place, as Mike Bedford discovers through emulation.
Create and use inventory objects
Nate Drake invites you to relive the glory days of point-and-click adventure games by creating your very own.
ADMINISTERIA
Manage network downloads locally
Find out how to apply some admin knowledge to network downloads.
Farewell, Docker; hello, Rancher Desktop
Introducing yet another – better – way to manage your containers.
LINUX L APTOPS
Stuart Burns is a Linux administrator for a
HDDs up, this is a RAID!
Handy admin tips for locating those many drives in your redundant arrays.
AccuWeb Hosting
Power-packed web hosting for all levels of user, including the ever-so-picky Mike Williams.
Smartproxy
Sead Fadilpašić tests a versatile and fairly affordable proxy service.
Green PC Machines
The world’s biggest PC maker says it can achieve net zero by 2050. Barry Collins visits its US headquarters to get his hands on plant-based PCs, bamboo packaging and vegan leatherstyle covers.
CODING ACADEMY
Write your own Android application
Matt Holder investigates how to create cross-platform applications using a combination of Python and the Kivy framework.
Chat
X
Pocketmags Support