Skip to content

x0141af92ax/pipex

Repository files navigation

🚰 Pipex

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.

📝 Description

The program mimics the following shell command:

< infile cmd1 | cmd2 > outfile

It 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.

🛠️ Usage

Compilation

To compile the program, run:

make

Syntax

./pipex infile "cmd1" "cmd2" outfile

Arguments

  • 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).

Examples

Count lines in a file:

./pipex input.txt "cat" "wc -l" result.txt
# Equivalent to: < input.txt cat | wc -l > result.txt

Find a specific word:

./pipex input.txt "grep hello" "awk '{print $1}'" result.txt
# Equivalent to: < input.txt grep hello | awk '{print $1}' > result.txt

⚙️ How It Works

The 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]

🛡️ Error Handling & Memory Safety

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.

📂 Project Structure

.
├── 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

👨‍💻 Author

rsbaa (42 Student)

About

A C implementation of the UNIX mechanism pipe. This project mimics the behavior of the shell command < infile cmd1 | cmd2 > outfile, handling process creation, file descriptor redirection, and execution.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors