Unix Redirection In C
This short post is a recount of an exploration into redirection in the C language.
As always, let's go to our friend Wikipedia to set the definition for us:
In computing, redirection is a form of interprocess communication, and is a function common to most command-line interpreters, including the various Unix shells that can redirect standard streams to user-specified locations.
In Unix-like operating systems, programs do redirection with the dup2(2) system call, or its less-flexible but higher-level stdio analogues, freopen(3) and popen(3).
Basic redirection can use
< to redirect input and
> to redirect output.
For example, we can use the redirect output operator to redirect the output from
echo "Hello!" into a file
As mentioned by our pal Wikipedia, we can use the
dup2 system call in C to manage a similar thing!
A simple example
In our first example, we are going to write a simple example of two variables that open a
foobar.txt that iterates character by character.
foobar.txt, add th following:
As for the contents of
The comments in the code explain what is happening in order, but we're just going to print out the result by running
gcc one.c && ./a.out. The output binary
a.out is the name given since we do not provide output to GCC.
To explain further what is going on:
- We assign
- We use
readto read in a character and assign it to variable
- Each time we read
fd2, we move one character further along in the text file.
- Eventually, we read
fd1once and then we redirect
- We read
fd2one last time, but after redirection the value now reads "o".
A more readable example
The above can seem hard to comprehend - it is better playing around with this stuff in C. This example, I decided to use
scanf to read in from stdin in the second example, because I feel like the example was a little clearer for me.
Note: Given I knew the length of the words in the file, I just set a max STR_LEN of 6 as opposed to some dynamic calculation.
Create a file
Now if we run
gcc two.c && ./a.out, we get the following:
In this case, we do the following:
- Allocate memory for
- Confirm no values in first print.
- Read in the
foobar.txtfile to file descriptor
scanfto assign the values to
- Confirm with the last print that
c2have been assigned the words "foobar" and "test" respectively!
Hooray! Redirection to stdin is a success (and no segmentation faults).
I will likely redo this exercise in Rust and Golang this week to show the how-to.
- Computer Systems A Programmer's Perspective - Page 944
- dup2 System Call
- Stack Overflow - difference between read and fread
- Unix System Calls - read
- Top 20 C Pointer Mistakes
- Stack Overflow - Reading file and getting string length
- CS 702 Operating Systems - redirect and pipes
- TutorialsPoint - Redirection
- Redirection - Wikipedia
Image credit: Michael Kubler
1,200+ PEOPLE ALREADY JOINED ❤️️
Get fresh posts + news direct to your inbox.
No spam. We only send you relevant content.