Pipex

A C program that simulates the behavior of shell pipes, handling process creation and execution.

2021-08-01

low-levelOpen GitHub
Pipex

Pipex

A C program that replicates what the shell does when you write < infile cmd1 | cmd2 > outfile. Two child processes, one pipe, file descriptor redirections, and execve calls. The result is functionally identical to the shell version.

Usage

./pipex infile "cmd1" "cmd2" outfile
# same as: < infile cmd1 | cmd2 > outfile
 
./pipex input.txt "grep hello" "wc -l" output.txt

Bonus - multiple pipes:

./pipex infile "cmd1" "cmd2" "cmd3" outfile
# same as: < infile cmd1 | cmd2 | cmd3 > outfile

Bonus - heredoc:

./pipex here_doc LIMITER "cmd1" "cmd2" outfile
# same as: cmd1 << LIMITER | cmd2 >> outfile

How it works

[infile] --> [child1: cmd1] --pipe--> [child2: cmd2] --> [outfile]
                   |                        |
                 fork()                   fork()
                   +-------- parent -------+
                                 |
                             waitpid()
  1. Parent opens infile and outfile
  2. Creates a pipe (read end and write end)
  3. Child 1 redirects stdin from infile, stdout to the pipe write end, runs cmd1
  4. Child 2 redirects stdin from the pipe read end, stdout to outfile, runs cmd2
  5. Parent waits for both

Commands are looked up from $PATH.

Errors

SituationWhat happens
infile missing or unreadablePrints error, exits
outfile can't be createdPrints error, exits
Command not found in PATHPrints "command not found", child exits
pipe() or fork() failsSystem error printed, exits

SCREENSHOTS // 01 FRAMES

Screenshot 1
01 / 01