210 words
1 minute
Pipex — UNIX Pipeline Simulation and Process Management in C
Pipex — UNIX Pipeline and Process Redirection
Pipex replicates the core mechanism of UNIX shell pipelines in C, handling process creation, pipe IPC, and file descriptor management.
# Shell syntax:< infile cmd1 | cmd2 > outfile
# Pipex execution:./pipex infile "cmd1" "cmd2" outfileSystem Calls and Mechanics
1. Inter-Process Communication via pipe()
The kernel allocates a unidirectional buffer managed by two file descriptors:
fd[0]: Read end.fd[1]: Write end.
int pipe_fd[2];if (pipe(pipe_fd) == -1) error_exit("pipe failure");2. File Descriptor Duplication via dup2()
In each forked child, standard streams are replaced before invoking execve:
- First Child (
cmd1): Standard input is redirected frominfile, standard output is redirected topipe_fd[1]. - Second Child (
cmd2): Standard input is redirected frompipe_fd[0], standard output is redirected tooutfile.
void child_one(char **argv, char **envp, int *pipe_fd){ int infile = open(argv[1], O_RDONLY); if (infile < 0) error_exit(argv[1]); dup2(infile, STDIN_FILENO); dup2(pipe_fd[1], STDOUT_FILENO); close(pipe_fd[0]); close(pipe_fd[1]); close(infile); execute_command(argv[2], envp);}3. Command Path Resolution
The program parses the PATH variable from envp, iterates through candidate directories, verifies access permissions with access(F_OK | X_OK), and executes the binary via execve.
Bonus: Arbitrary Multi-Pipe Chains and Heredoc
- Arbitrary Pipelines: Dynamic creation of pipes for commands:
Terminal window ./pipex infile "cmd1" "cmd2" "cmd3" ... "cmdN" outfile - Heredoc (
<<): Replicatingcmd << LIMITER | cmd1 >> outfileby buffering input from standard input until the limiter string is detected.
Sphynx | Ismail Larhrib