Pipex is a 42 School project that aims to replicate the behavior of the Unix pipe operator | in C. It handles file redirection, process creation, and inter-process communication using pipes.
The program mimics the following shell command:
< infile cmd1 | cmd2 > outfileIt takes an input file, processes its content with a first command, pipes the output to a second command, and saves the final result to an output file.
Compilation
To compile the program, run:
makeSyntax
./pipex infile "cmd1" "cmd2" outfileArguments
- infile: The file to read data from (Standard Input).
- cmd1: The first shell command (e.g., "ls -l").
- cmd2: The second shell command (e.g., "wc -l").
- outfile: The file to write the result to (Standard Output).
Count lines in a file:
./pipex input.txt "cat" "wc -l" result.txt
# Equivalent to: < input.txt cat | wc -l > result.txtFind a specific word:
./pipex input.txt "grep hello" "awk '{print $1}'" result.txt
# Equivalent to: < input.txt grep hello | awk '{print $1}' > result.txtThe program uses the following system calls to manage data flow:
- pipe(): Creates a unidirectional data channel.
- fork(): Splits the process into a Child 1 and a Child 2.
- dup2(): Swaps the Standard Input/Output file descriptors with the pipe ends or files.
- execve(): Replaces the current process memory with the command binary (e.g., /bin/ls).
Data Flow Diagram
graph LR
A[Infile] -->|stdin| B(Child Process 1)
B -->|execve cmd1| C{PIPE}
C -->|stdout to stdin| D(Child Process 2)
D -->|execve cmd2| E[Outfile]This implementation is robust and handles various edge cases:
- Memory Safety: 100% Valgrind clean. All allocated memory (split paths, arguments) is freed correctly.
- File Permissions: Checks if infile exists/is readable and if outfile is writable.
- Command Validation: Checks PATH to find binaries. If a command doesn't exist, it prints a clean error and returns the correct exit status.
.
├── Makefile # Compilation rules
├── pipex.h # Header file with prototypes
├── pipex.c # Main program logic (forks & pipes)
├── utils_1.c # Path parsing and execution logic
├── utils_2.c # String helpers (ft_strlen, ft_strjoin...)
├── utils_3.c # Error handling
└── utils_4.c # ft_split implementation
rsbaa (42 Student)