Replicate shell pipe behavior between two commands in C
A program that simulates the shell pipe operator. Given an input file, two commands, and an output file, it executes the equivalent of:
< infile cmd1 | cmd2 > outfile┌─────────┐ pipe() ┌─────────┐
│ CHILD 1 │──────────────▶│ CHILD 2 │
│ (cmd1) │ fd[0]/fd[1] │ (cmd2) │
└─────────┘ └─────────┘
▲ │
│ ▼
infile outfile
- Create a pipe with
pipe() - Fork first child: redirect
infile → stdin,pipe[1] → stdout, executecmd1 - Fork second child: redirect
pipe[0] → stdin,outfile → stdout, executecmd2 - Parent closes pipe ends and waits for both children
make # compiles pipex
make clean # removes .o files
make fclean # removes .o and binary
make re # full recompile./pipex infile "cmd1" "cmd2" outfile# Equivalent to: < /etc/passwd grep root | wc -l > output.txt
./pipex /etc/passwd "grep root" "wc -l" output.txt
# Equivalent to: < input.txt cat | sort > sorted.txt
./pipex input.txt "cat" "sort" sorted.txt
# Equivalent to: < file.txt tr a-z A-Z | head -5 > result.txt
./pipex file.txt "tr a-z A-Z" "head -5" result.txtpipex/
├── include/
│ └── pipex.h # Prototypes and includes
├── src/
│ ├── main.c # Entry point: pipe creation, fork, wait
│ ├── process.c # Child processes: fd redirection + execve
│ ├── path.c # PATH resolution: find executable binary
│ └── utils.c # ft_split, ft_strjoin_path, error handling
├── Makefile
└── .gitignore
| Module | Responsibility |
|---|---|
main.c |
Orchestrates pipe, forks, and waits |
process.c |
Redirects fds and executes commands |
path.c |
Searches PATH directories for binaries |
utils.c |
String splitting, path joining, error handling |
| Case | Behavior |
|---|---|
| Wrong number of arguments | Prints usage message |
| Input file doesn't exist | Prints error, child exits |
| Output file can't be created | Prints error, child exits |
| Command not found | Prints error, exits with code 127 |
| Command can't execute | Prints error, exits with code 126 |
Developed as part of the 42 Madrid curriculum. The project focuses on UNIX processes (fork, execve), file descriptors (pipe, dup2), and inter-process communication.