Anonymous pipes for parent-child IPC. Progresses from the shell pipe operator through the pipe() system call, byte-by-byte reading, dup2 for stdin/stdout redirection, bidirectional communication with two pipes, and an introduction to named pipes (mkfifo).
pipe(fd) creates a one-way data channel. After fork(), the parent writes to fd[1] and the child reads from fd[0]. Each side closes the end it doesn't use.
1
Pipe Concepts
Conceptual overview of how pipes work — unidirectional byte streams between related processes.
01-basics.c40 lines
/*this is a pure text file, no code herewe are talking about pipesIntroduction to PipesWhat is a Pipe?Definition: A pipe is a unidirectional communication channel that allows data to flow from one process to another.Purpose: Facilitates IPC by enabling the output of one process to be used as the input of another.Types:Anonymous Pipes: Typically used between parent and child processes. (the pipe() system call)Named Pipes (FIFOs): Persist in the filesystem and can be used between unrelated processes. (mkfifo() system call)Pipe CharacteristicsUnidirectional: Data flows in one direction. (meaning the other way around is closed while the data is flowing)Byte Streams: Data is treated as a continuous stream of bytesLimited Buffer Size: POSIX defines a minimum (or maximum atomic) buffer size (PIPE_BUF) - anything less and equal to PIPE_BUF happens atomically (guaranteed to be written/read in one go)The Pipe | OperatorPurpose: Connects the standard output (stdout) of one command to the standard input (stdin) of another.Example:$ ls -l | grep "file"or:cat file.txt | sort | uniqDisplays unique sorted lines from file.txt.*/
Editing — changes sent to terminal on Run
Reference — not run on its ownPipe basics explained in comments — no main() to run.
2
Shell Pipe Producer
A program that writes to stdout, designed to be piped on the shell command line.
02-pipe-operator-with-programs/producer.c30 lines
/* * producer.c — Producer — writes data to stdout (used with shell pipe) * * Key concepts: printf to stdout, paired with consumer via pipe operator * Compile: gcc -o producer producer.c * Run: ./prog *//// the producer program will write data to stdout// we need to run both compiled programs (consumer and producer) : ./producer | ./consumer#include <stdio.h>#include <unistd.h>int main(int argc, char const *argv[]){ // The banner goes to stderr: stdout is the pipe, and only the data may travel through it fprintf(stderr, "\n"); fprintf(stderr, "══════════════════════════════════════\n"); fprintf(stderr, " Producer\n"); fprintf(stderr, "══════════════════════════════════════\n\n"); fprintf(stderr, "[Producer PID %d] Writing data to stdout...\n", getpid()); fprintf(stderr, "[Producer] Usage: ./producer | ./consumer\n"); printf("Yaniv\n"); fprintf(stderr, "[Producer PID %d] Wrote \"Yaniv\" to stdout. Exiting.\n", getpid()); return 0;}
══════════════════════════════════════
Producer
══════════════════════════════════════
[Producer PID 1619] Writing data to stdout...
[Producer] Usage: ./producer | ./consumer
Yaniv
[Producer PID 1619] Wrote "Yaniv" to stdout. Exiting.
3
Shell Pipe Consumer
A program that reads from stdin, completing the shell pipe: ./producer | ./consumer.
02-pipe-operator-with-programs/consumer.c29 lines
/* * consumer.c — Consumer — reads from stdin (used with shell pipe) * * Key concepts: scanf from stdin, paired with producer: ./producer | ./consumer * Compile: gcc -o consumer consumer.c * Run: ./prog *//// the consumer program will read the output of the producer program using stdin// we need to run both compiled programs (consumer and producer) : ./producer | ./consumer#include <stdio.h>#include <unistd.h>int main(int argc, char const *argv[]){ printf("\n"); printf("══════════════════════════════════════\n"); printf(" Consumer\n"); printf("══════════════════════════════════════\n\n"); fprintf(stderr, "[Consumer PID %d] Reading from stdin...\n", getpid()); char buffer[100]; scanf("%99s", buffer); // at most 99 chars + '\0' — never overflow the buffer printf("[Consumer PID %d] Received via pipe: \"%s\"\n", getpid(), buffer); return 0;}
══════════════════════════════════════
Consumer
══════════════════════════════════════
[Consumer PID 1644] Reading from stdin...
══════════════════════════════════════
Producer
══════════════════════════════════════
[Producer PID 1643] Writing data to stdout...
[Producer] Usage: ./producer | ./consumer
[Producer PID 1643] Wrote "Yaniv" to stdout. Exiting.
[Consumer PID 1644] Received via pipe: "Yaniv"
4
pipe() System Call
Using pipe() to create a pipe in code, then fork() so the parent writes and the child reads.
03-pipe-system-call.c133 lines
/* * 03-pipe-system-call.c — The pipe() system call: parent writes, child reads * * Demonstrates: Creating pipes, fork+pipe pattern, closing unused ends * Key concepts: pipefd[0]=read, pipefd[1]=write, EOF detection, kernel buffer * Compile: gcc -o pipe_call 03-pipe-system-call.c * Run: ./pipe_call */#include <unistd.h> // for pipe(), fork(), read(), write(), close()#include <stdio.h>#include <stdlib.h>#include <string.h>#include <sys/types.h> // for pid_t/*Understanding Pipe File Descriptors After forkWhen you create a pipe using pipe(pipefd), it generates two file descriptors:pipefd[0]: The read end of the pipe.pipefd[1]: The write end of the pipe.After calling fork(), both the parent and child processes inherit copies of these file descriptors. This means:Parent Process:Has access to both pipefd[0] (read) and pipefd[1] (write).Child Process:Also has access to both pipefd[0] (read) and pipefd[1] (write).However, for effective IPC, it's essential to close the unused ends in each process to prevent unintended behavior, such as deadlocks or resource leaks.so the situation can be visualized as follows:Before fork():Parent Process:- pipefd[0] (read end)- pipefd[1] (write end)After fork():Parent Process:- pipefd[0] (closed)- pipefd[1] (write end, used to write data)Child Process:- pipefd[0] (read end, used to read data)- pipefd[1] (closed)Tips:- Always check the return values of system calls (pipe, fork, read, write, etc.) and handle errors appropriately.- Always check the return values of read and write to handle cases where not all data is read or written in one operation.- Always Close Unused Ends: After creating a pipe, close the unused ends in the parent and child processes to avoid issues like deadlocks.- Use sleep() or other synchronization mechanisms to ensure that the child process is ready to read before the parent writes data to the pipe.- Of course : Use waitpid or wait in the parent process to wait for child processes to prevent zombie processes.- EOF Detection: When the parent closes pipefd[1] after writing, the child’s read operation can detect EOF, allowing it to know that no more data will be sent.- Basicly while read is > 0, the child will keep reading from the pipe, when it reaches EOF (recived 0) it will stop.But how does it actually works?a. Writing Data:Parent Writes to pipefd[1]:The write system call in the parent writes data to the write end of the pipe.This data is placed into a kernel-managed buffer associated with the pipe.The data remains in the buffer until it is read by the child process.if the buffer is full, the write operation will block until space is available in the buffer (probably the child is not reading from the pipe).but its unlikely to happen, because the buffer size is 65536 bytes (64KB) in linux.b. Reading DataChild Reads from pipefd[0]:The read system call in the child reads data from the read end of the pipe.The data read is the same data that the parent wrote to pipefd[1].If there is no data available to read, the read operation will block until data is written to the pipe.When the parent closes pipefd[1], the child’s read operation will return 0, indicating EOF (end of file).*/int main() { printf("\n"); printf("══════════════════════════════════════\n"); printf(" pipe() System Call\n"); printf(" Parent writes → Child reads\n"); printf("══════════════════════════════════════\n\n"); int pipefd[2]; pid_t pid; char buffer[100]; if (pipe(pipefd) == -1) { perror("pipe"); exit(EXIT_FAILURE); } printf("[Setup] pipe() created: read_fd=%d, write_fd=%d\n\n", pipefd[0], pipefd[1]); pid = fork(); if (pid == 0) { // Child process close(pipefd[1]); // Close unused write end //arguments of read: //1. file descriptor //2. buffer to read into //3. how many bytes to read /* yoram showed: הקורא, על-כן יבצע משהו כמו:while (read(my_pipe[0], &c, 1) > 0)// which will read one byte at a time until EOF// sometimes that approach is better (safer) than reading all at once// sometimes its slower */ sleep(2); // why this sleep here, will make the program get stuck? // why its bad? and why its better to put the sleep before the write? ssize_t bytesRead = read(pipefd[0], buffer, sizeof(buffer)); // Read from the pipe if (bytesRead == -1) { perror("read"); exit(EXIT_FAILURE); } printf("[Child PID %d] Received from pipe: \"%s\" (%ld bytes)\n", getpid(), buffer, (long)bytesRead); printf("[Child PID %d] String length: %ld\n", getpid(), strlen(buffer)); close(pipefd[0]); exit(EXIT_SUCCESS); } else { // Parent process close(pipefd[0]); // Close unused read end // sleep(2); printf("[Parent PID %d] Writing to pipe: \"Hello, Pipe!\"\n", getpid()); ssize_t bytesWritten = write(pipefd[1], "Hello, Pipe!", strlen("Hello, Pipe!") + 1); if (bytesWritten == -1) { perror("write"); exit(EXIT_FAILURE); } printf("[Parent PID %d] Wrote %ld bytes. Closing write end.\n", getpid(), (long)bytesWritten); close(pipefd[1]); } return 0;}
Parent writes character-by-character into a pipe, child reads it all. Demonstrates pipe buffering, closing the write end to signal EOF, and how read() returns 0 at end-of-stream.
04-more-pipe.c74 lines
/* * 04-more-pipe.c — More pipe examples — parent/child communication * * Key concepts: pipe(), fork(), read/write, closing unused ends * Compile: gcc -o more_pipe 04-more-pipe.c * Run: ./prog */#include <unistd.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <sys/types.h>#define BUFFER_SIZE 1024/*Parent Writing All Data Before Child Reads:The parent writes the message character by character into the pipe. Since write() is non-blocking (buffer has enough space), the parent continues writing without waiting for the child to read each character.The child only begins to process data when it executes its read() loop after the parent's write() calls have already started.Closing the Write End:When the parent closes my_pipe[1], it signals EOF to the child. This EOF is not immediately "received" by the child but is interpreted as the end of the data stream when the child has read all the buffered data.After closing the write end, the child's read() detects EOF (when read() returns 0) and exits the loop.*/int main() { printf("\n"); printf("══════════════════════════════════════\n"); printf(" Pipe: Char-by-Char Write, Bulk Read\n"); printf(" Parent writes loop → Child reads all\n"); printf("══════════════════════════════════════\n\n"); int pipefd[2]; pid_t pid; ssize_t bytes; char buffer[BUFFER_SIZE]; if (pipe(pipefd) == -1) { perror("pipe"); exit(EXIT_FAILURE); } pid = fork(); if (pid == 0) { // Child: Reader close(pipefd[1]); // Close write end while ((bytes = read(pipefd[0], buffer, sizeof(buffer)-1)) > 0) { buffer[bytes] = '\0'; printf("[Child PID %d] Read %ld bytes: \"%s\"", getpid(), (long)bytes, buffer); } close(pipefd[0]); exit(EXIT_SUCCESS); } else { // Parent: Writer close(pipefd[0]); // Close read end const char *msg = "Hello, this is a message from the parent.\n"; printf("[Parent PID %d] Writing %ld bytes to pipe...\n", getpid(), (long)strlen(msg)); size_t len = strlen(msg); ssize_t total_written = 0; while (total_written < len) { bytes = write(pipefd[1], msg + total_written, len - total_written); if (bytes == -1) { perror("write"); break; } total_written += bytes; } close(pipefd[1]); } return 0;}
Editing — changes sent to terminal on Run
$ gcc -o more_pipe 04-more-pipe.c
$ ./more_pipe
Expected Outputclick Run to execute live
══════════════════════════════════════
Pipe: Char-by-Char Write, Bulk Read
Parent writes loop → Child reads all
══════════════════════════════════════
[Parent PID 1712] Writing 42 bytes to pipe...
[Child PID 1713] Read 42 bytes: "Hello, this is a message from the parent.
"student:~$
7
Pipe with File Descriptors
Working directly with pipe file descriptors — read end (fd[0]) and write end (fd[1]).
05-pipe-with-fd.c55 lines
/* * 05-pipe-with-fd.c — Using pipes with file descriptor operations * * Key concepts: pipe(), file descriptors, read/write * Compile: gcc -o pipe_fd 05-pipe-with-fd.c * Run: ./prog */#include <unistd.h>#include <stdio.h>#include <stdlib.h>#include <sys/types.h>int main() { printf("\n"); printf("══════════════════════════════════════\n"); printf(" Pipe with FILE* (fdopen)\n"); printf(" Use fprintf/fscanf instead of raw read/write\n"); printf("══════════════════════════════════════\n\n"); int pipefd[2]; pid_t pid; char buffer[100]; FILE *read_fp, *write_fp; if (pipe(pipefd) == -1) { perror("pipe"); exit(EXIT_FAILURE); } pid = fork(); if (pid == 0) { // Child: Reader close(pipefd[1]); // Close write end read_fp = fdopen(pipefd[0], "r"); if (read_fp == NULL) { perror("fdopen"); exit(EXIT_FAILURE); } fscanf(read_fp, "%99s", buffer); printf("[Child PID %d] Read via FILE*/fscanf: \"%s\"\n", getpid(), buffer); fclose(read_fp); exit(EXIT_SUCCESS); } else { // Parent: Writer close(pipefd[0]); // Close read end printf("[Parent PID %d] Writing via FILE*/fprintf...\n", getpid()); write_fp = fdopen(pipefd[1], "w"); if (write_fp == NULL) { perror("fdopen"); exit(EXIT_FAILURE); } fprintf(write_fp, "Hello_File_Stream\n"); fclose(write_fp); } return 0;}
Editing — changes sent to terminal on Run
$ gcc -o pipe_fd 05-pipe-with-fd.c
$ ./pipe_fd
Expected Outputclick Run to execute live
══════════════════════════════════════
Pipe with FILE* (fdopen)
Use fprintf/fscanf instead of raw read/write
══════════════════════════════════════
[Parent PID 1731] Writing via FILE*/fprintf...
[Child PID 1732] Read via FILE*/fscanf: "Hello_File_Stream"
8
dup2 + exec Pattern
The classic pattern: dup2 to redirect stdin/stdout to pipe ends, then exec a child program that reads/writes normally.
06-pipe-exec-dup.c146 lines
/* * 06-pipe-exec-dup.c — Connecting two programs with pipe + dup2 + exec * * Demonstrates: The dup2() pattern for redirecting stdin/stdout through a pipe * Key concepts: dup2(), execlp(), producer-consumer via pipe, fd cleanup * Compile: gcc -o pipe_exec 06-pipe-exec-dup.c * (also compile producer.c and consumer.c from 02-pipe-operator-with-programs/) * Run: ./pipe_exec * * This implements the equivalent of: ./producer | ./consumer * but programmatically using fork + pipe + dup2 + exec. */#include <unistd.h> // for pipe(), fork(), dup2(), execlp(), close()#include <stdio.h>#include <stdlib.h>#include <sys/types.h> // for pid_t#include <sys/wait.h> // for waitpid()/*File Descriptor Duplication:The dup2(pipefd[1], STDOUT_FILENO) in the producer process duplicates the write end of the pipe (pipefd[1]) into the standard output file descriptor (STDOUT_FILENO).Similarly, dup2(pipefd[0], STDIN_FILENO) in the consumer process duplicates the read end of the pipe (pipefd[0]) into the standard input file descriptor (STDIN_FILENO).*//* pipe is created using pipe(pipefd).pipefd[0]: Read end of the pipe.pipefd[1]: Write end of the pipe.The program forks two child processes:The producer writes to the pipe.The consumer reads from the pipe.The producer and consumer are executed as separate programs using execlp().The parent process handles cleanup and waits for both children to finish.*//*dup2(pipefd[1], STDOUT_FILENO) duplicates the write end of the pipe into the standard output (STDOUT_FILENO).This means anything the producer writes to stdout will go into the pipe.Cleanup:The producer doesn't need pipefd[0] (read end), so it closes it.The original pipefd[1] is also closed because dup2() has already duplicated it.*//*Redirection:dup2(pipefd[0], STDIN_FILENO) duplicates the read end of the pipe into the standard input (STDIN_FILENO).This means the consumer will read its input from the pipe instead of the terminal.Cleanup:The consumer doesn't need pipefd[1] (write end), so it closes it.The original pipefd[0] is also closed after dup2().*/int main() { printf("\n"); printf("══════════════════════════════════════\n"); printf(" pipe + dup2 + exec\n"); printf(" Programmatic: ./producer | ./consumer\n"); printf("══════════════════════════════════════\n\n"); int pipefd[2]; pid_t pid_producer, pid_consumer; if (pipe(pipefd) == -1) { perror("pipe"); exit(EXIT_FAILURE); } // Fork producer process pid_producer = fork(); if (pid_producer == -1) { perror("fork"); exit(EXIT_FAILURE); } printf("[Parent PID %d] pipe() created: read_fd=%d, write_fd=%d\n", getpid(), pipefd[0], pipefd[1]); if (pid_producer == 0) { // Producer Child // Redirect stdout to pipe's write end if (dup2(pipefd[1], STDOUT_FILENO) == -1) { perror("dup2"); exit(EXIT_FAILURE); } close(pipefd[0]); // Close unused read end close(pipefd[1]); // Close original write end // Execute producer program execlp("./producer", "./producer", (char *)NULL); perror("execlp producer"); exit(EXIT_FAILURE); } // Fork consumer process pid_consumer = fork(); if (pid_consumer == -1) { perror("fork"); exit(EXIT_FAILURE); } if (pid_consumer == 0) { // Consumer Child // Redirect stdin to pipe's read end if (dup2(pipefd[0], STDIN_FILENO) == -1) { perror("dup2"); exit(EXIT_FAILURE); } close(pipefd[1]); // Close unused write end close(pipefd[0]); // Close original read end // Execute consumer program execlp("./consumer", "./consumer", (char *)NULL); perror("execlp consumer"); exit(EXIT_FAILURE); } printf("[Parent] Forked producer (PID %d) and consumer (PID %d).\n", pid_producer, pid_consumer); printf("[Parent] dup2: producer stdout → pipe write end, consumer stdin → pipe read end.\n"); printf("[Parent] Closing pipe fds and waiting for children...\n\n"); close(pipefd[0]); close(pipefd[1]); waitpid(pid_producer, NULL, 0); waitpid(pid_consumer, NULL, 0); printf("[Parent] Both children finished.\n"); return 0;}
Editing — changes sent to terminal on Run
$ gcc -o pipe_dup 06-pipe-exec-dup.c
$ ./pipe_dup
Expected Outputclick Run to execute live
══════════════════════════════════════
pipe + dup2 + exec
Programmatic: ./producer | ./consumer
══════════════════════════════════════
[Parent PID 1749] pipe() created: read_fd=3, write_fd=4
[Parent PID 1750] pipe() created: read_fd=3, write_fd=4
execlp producer: No such file or directory
[Parent] Forked producer (PID 1750) and consumer (PID 1751).
[Parent] dup2: producer stdout → pipe write end, consumer stdin → pipe read end.
[Parent] Closing pipe fds and waiting for children...
execlp consumer: No such file or directory
[Parent] Both children finished.
9
Bidirectional Communication
Using two pipes for two-way parent-child communication — one pipe per direction.
07-two-ways-communication.c117 lines
/* * 07-two-ways-communication.c — Bidirectional IPC using two pipes * * Demonstrates: Two-way parent-child communication with a pair of pipes * Key concepts: One pipe per direction (pipes are unidirectional!), fd cleanup * Compile: gcc -o two_way 07-two-ways-communication.c * Run: ./two_way * * Architecture: * pipe1: Parent --write--> pipe1_fd[1] ... pipe1_fd[0] --read--> Child * pipe2: Child --write--> pipe2_fd[1] ... pipe2_fd[0] --read--> Parent */#include <unistd.h> // for pipe(), fork(), read(), write(), close()#include <stdio.h>#include <stdlib.h>#include <string.h>#include <sys/types.h> // for pid_t#include <sys/wait.h> // for wait()#define BUFFER_SIZE 100int main() { printf("\n"); printf("══════════════════════════════════════\n"); printf(" Bidirectional IPC — Two Pipes\n"); printf(" pipe1: Parent→Child, pipe2: Child→Parent\n"); printf("══════════════════════════════════════\n\n"); int pipe1_fd[2]; // Pipe 1: parent writes, child reads int pipe2_fd[2]; // Pipe 2: child writes, parent reads pid_t pid; char buffer[BUFFER_SIZE]; // Create first pipe (parent to child) if (pipe(pipe1_fd) == -1) { perror("pipe1"); exit(EXIT_FAILURE); } // Create second pipe (child to parent) if (pipe(pipe2_fd) == -1) { perror("pipe2"); exit(EXIT_FAILURE); } // Fork the process pid = fork(); if (pid == -1) { // Error handling for fork perror("fork"); exit(EXIT_FAILURE); } if (pid == 0) { // Child Process // Close unused ends close(pipe1_fd[1]); // Close write end of pipe1 close(pipe2_fd[0]); // Close read end of pipe2 // Read message from parent ssize_t bytesRead = read(pipe1_fd[0], buffer, sizeof(buffer) - 1); if (bytesRead == -1) { perror("Child read from pipe1"); exit(EXIT_FAILURE); } buffer[bytesRead] = '\0'; // Null-terminate the string printf("[Child PID %d] Received from parent via pipe1: \"%s\"\n", getpid(), buffer); // Prepare response printf("[Child PID %d] Sending reply via pipe2...\n", getpid()); const char *child_msg = "Hello from Child!"; ssize_t bytesWritten = write(pipe2_fd[1], child_msg, strlen(child_msg) + 1); if (bytesWritten == -1) { perror("Child write to pipe2"); exit(EXIT_FAILURE); } // Close used ends close(pipe1_fd[0]); close(pipe2_fd[1]); exit(EXIT_SUCCESS); } else { // Parent Process // Close unused ends close(pipe1_fd[0]); // Close read end of pipe1 close(pipe2_fd[1]); // Close write end of pipe2 // Send message to child printf("[Parent PID %d] Sending message to child via pipe1...\n", getpid()); const char *parent_msg = "Hello from Parent!"; ssize_t bytesWritten = write(pipe1_fd[1], parent_msg, strlen(parent_msg) + 1); if (bytesWritten == -1) { perror("Parent write to pipe1"); exit(EXIT_FAILURE); } // Read response from child ssize_t bytesRead = read(pipe2_fd[0], buffer, sizeof(buffer) - 1); if (bytesRead == -1) { perror("Parent read from pipe2"); exit(EXIT_FAILURE); } buffer[bytesRead] = '\0'; // Null-terminate the string printf("[Parent PID %d] Received from child via pipe2: \"%s\"\n", getpid(), buffer); // Close used ends close(pipe1_fd[1]); close(pipe2_fd[0]); // Wait for child to finish if (wait(NULL) == -1) { perror("wait"); exit(EXIT_FAILURE); } } return 0;}
Editing — changes sent to terminal on Run
$ gcc -o two_way 07-two-ways-communication.c
$ ./two_way
Expected Outputclick Run to execute live
══════════════════════════════════════
Bidirectional IPC — Two Pipes
pipe1: Parent→Child, pipe2: Child→Parent
══════════════════════════════════════
[Parent PID 1779] Sending message to child via pipe1...
[Child PID 1780] Received from parent via pipe1: "Hello from Parent!"
[Child PID 1780] Sending reply via pipe2...
[Parent PID 1779] Received from child via pipe2: "Hello from Child!"
10
Bidirectional Parent (dup2)
Parent side of a two-way pipe setup using dup2 for clean fd management.
08-two-ways-with-dupes/parent-program.c133 lines
/* * parent-program.c — Parent with dup2 — redirected stdin/stdout for child * * Key concepts: dup2(), fork(), exec(), bidirectional pipe communication * Compile: gcc -o parent parent-program.c * Run: ./prog */// parent_program.c#include <unistd.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <sys/types.h>#include <sys/wait.h>/*this is a bit confusing examplebut we will need to scheme it on the board to better udnerstandwe use two pipes to communicate between parent and childusing dupes , the stdout of the parent goes to the child (to its std in)and the stdout of the child comes back to the parent (to its std in)*/#define BUFFER_SIZE 100int main() { printf("\n"); printf("══════════════════════════════════════\n"); printf(" Bidirectional dup2 + exec\n"); printf(" Parent ↔ Child via redirected stdio\n"); printf("══════════════════════════════════════\n\n"); int pipe_parent_to_child[2]; int pipe_child_to_parent[2]; pid_t pid; char buffer[BUFFER_SIZE]; // Create pipe for parent to child communication if (pipe(pipe_parent_to_child) == -1) { perror("pipe_parent_to_child"); exit(EXIT_FAILURE); } // Create pipe for child to parent communication if (pipe(pipe_child_to_parent) == -1) { perror("pipe_child_to_parent"); exit(EXIT_FAILURE); } // Fork the process pid = fork(); if (pid == -1) { // Error handling for fork perror("fork"); exit(EXIT_FAILURE); } if (pid == 0) { // Child Process // Redirect stdin to read from pipe_parent_to_child if (dup2(pipe_parent_to_child[0], STDIN_FILENO) == -1) { perror("dup2 stdin"); exit(EXIT_FAILURE); } // Redirect stdout to write to pipe_child_to_parent if (dup2(pipe_child_to_parent[1], STDOUT_FILENO) == -1) { perror("dup2 stdout"); exit(EXIT_FAILURE); } // Close unused file descriptors close(pipe_parent_to_child[0]); close(pipe_parent_to_child[1]); close(pipe_child_to_parent[0]); close(pipe_child_to_parent[1]); // Execute the child program execlp("./child_program", "./child_program", (char *)NULL); // If exec fails perror("execlp"); exit(EXIT_FAILURE); } else { // Parent Process // Close unused file descriptors close(pipe_parent_to_child[0]); // Close read end of parent to child close(pipe_child_to_parent[1]); // Close write end of child to parent // Convert file descriptors to FILE* streams for easier I/O FILE *write_fp = fdopen(pipe_parent_to_child[1], "w"); if (write_fp == NULL) { perror("fdopen write_fp"); exit(EXIT_FAILURE); } FILE *read_fp = fdopen(pipe_child_to_parent[0], "r"); if (read_fp == NULL) { perror("fdopen read_fp"); exit(EXIT_FAILURE); } // Send message to child const char *message = "Hello from Parent Program!"; fprintf(stderr, "[Parent PID %d] Sending to child: \"%s\"\n", getpid(), message); fprintf(write_fp, "%s\n", message); fflush(write_fp); // Read response from child if (fgets(buffer, sizeof(buffer), read_fp) != NULL) { fprintf(stderr, "[Parent] Received from child: %s", buffer); } // Read second response from child if (fgets(buffer, sizeof(buffer), read_fp) != NULL) { fprintf(stderr, "[Parent] Received from child: %s", buffer); } // Close the streams fclose(write_fp); // Sends EOF to child fclose(read_fp); // Wait for child to finish if (wait(NULL) == -1) { perror("wait"); exit(EXIT_FAILURE); } } return 0;}
══════════════════════════════════════
Bidirectional dup2 + exec
Parent ↔ Child via redirected stdio
══════════════════════════════════════
[Parent PID 1803] Sending to child: "Hello from Parent Program!"
[Parent] Received from child:
[Parent] Received from child: ═════════════════════════════════student:~$
11
Bidirectional Child (dup2)
Child side that communicates with the parent through redirected stdin/stdout.
08-two-ways-with-dupes/child.c31 lines
/* * child.c — Child — reads stdin, writes stdout (duped from pipes) * * Key concepts: Reads from redirected stdin, writes to redirected stdout * Compile: gcc -o child child.c * Run: ./prog */// child_program.c#include <stdio.h>#include <string.h>int main() { printf("\n"); printf("══════════════════════════════════════\n"); printf(" Child\n"); printf("══════════════════════════════════════\n\n"); char buffer[100]; // Read message from parent (via redirected stdin ← pipe) if (fgets(buffer, sizeof(buffer), stdin) != NULL) { buffer[strcspn(buffer, "\n")] = '\0'; // stdout goes back to parent via the other pipe printf("[Child] Received from parent: \"%s\"\n", buffer); } printf("[Child] Sending reply back to parent.\n"); return 0;}
Editing — changes sent to terminal on Run
Reference — not run on its ownStarted by parent-program.c with exec (as ./child_program) — run that example.
12
Named Pipe Reader
Introduction to mkfifo — creating a named pipe on the filesystem and reading from it.
09-mkfifo/reader.c53 lines
/* * reader.c — Named pipe reader — intro to mkfifo (FIFO) * * Key concepts: mkfifo, open, read from named pipe * Compile: gcc -o reader reader.c * Run: ./prog */#include <stdio.h>#include <stdlib.h>#include <fcntl.h>#include <unistd.h>#include <string.h>#define FIFO_PATH "/tmp/my_fifo"// FIRST create the fifo like:// terminal -> mkfifo /tmp/my_fifo// than we can open 2 terminals// terminal 1: start the reader: (reading blocks remebebr!?!?!) ./reader// terminal 2: start the writer ./writerint main() { printf("\n"); printf("══════════════════════════════════════\n"); printf(" Named Pipe (FIFO) Reader\n"); printf(" First: mkfifo %s\n", FIFO_PATH); printf("══════════════════════════════════════\n\n"); char buffer[100]; printf("[Reader PID %d] Opening FIFO %s for reading...\n", getpid(), FIFO_PATH); printf("[Reader] (blocks until a writer opens the other end)\n"); fflush(stdout); int fifo_fd = open(FIFO_PATH, O_RDONLY); if (fifo_fd == -1) { perror("open"); exit(EXIT_FAILURE); } // Read the message from the FIFO ssize_t bytesRead = read(fifo_fd, buffer, sizeof(buffer) - 1); if (bytesRead == -1) { perror("read"); close(fifo_fd); exit(EXIT_FAILURE); } buffer[bytesRead] = '\0'; // Null-terminate the string printf("[Reader PID %d] Received %ld bytes: \"%s\"\n", getpid(), (long)bytesRead, buffer); close(fifo_fd); return 0;}
Editing — changes sent to terminal on Run
$ gcc -o fifo_reader 09-mkfifo/reader.c
$ mkfifo /tmp/my_fifo 2>/dev/null; ./fifo_reader
Talks to writer.c — use Run pair
13
Named Pipe Writer
Writing to a named pipe — run alongside the reader to see data flow between unrelated processes.
09-mkfifo/writer.c54 lines
/* * writer.c — Named pipe writer — writing to a FIFO * * Key concepts: open, write to named pipe, FIFO blocks until reader connects * Compile: gcc -o writer writer.c * Run: ./prog */#include <stdio.h>#include <stdlib.h>#include <fcntl.h>#include <unistd.h>#include <string.h>// FIRST create the fifo like:// terminal -> mkfifo /tmp/my_fifo// than we can open 2 terminals// terminal 1: start the reader: (reading blocks remebebr!?!?!) ./reader// terminal 2: start the writer ./writer#define FIFO_PATH "/tmp/my_fifo"int main() { printf("\n"); printf("══════════════════════════════════════\n"); printf(" Named Pipe (FIFO) Writer\n"); printf(" First: mkfifo %s\n", FIFO_PATH); printf("══════════════════════════════════════\n\n"); const char *message = "Hello from the Writer!\n"; printf("[Writer PID %d] Opening FIFO %s for writing...\n", getpid(), FIFO_PATH); printf("[Writer] (blocks until a reader opens the other end)\n"); fflush(stdout); int fifo_fd = open(FIFO_PATH, O_WRONLY); // you can also you File* fifo_fd = fopen(FIFO_PATH, "w"); if (fifo_fd == -1) { perror("open"); exit(EXIT_FAILURE); } // Write the message to the FIFO if (write(fifo_fd, message, sizeof(char) * strlen(message)) == -1) { perror("write"); close(fifo_fd); exit(EXIT_FAILURE); } printf("[Writer PID %d] Wrote %ld bytes to FIFO: \"%s\"\n", getpid(), (long)strlen(message), "Hello from the Writer!"); close(fifo_fd); return 0;}
Make the write() hit SIGPIPE: once no process holds the read end, writing kills the writer. The parent still holds one — close the end it does not use. Click Edit, change the code, then Run — the site checks how it ended.
sigpipe.c41 lines
/* * Challenge (Lesson 08): write into a pipe nobody reads * * The child closes its read end and exits. The parent then writes into the pipe. * Writing to a pipe with NO reader left raises SIGPIPE, whose default action kills * the writer — but right now the write succeeds. Why? The parent still holds a read * end itself, so the kernel thinks someone could still read. * * Your task: make the parent close the end it does not use, so the write hits SIGPIPE. * Done when the program is "Killed by SIGPIPE (13)". */#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include <sys/wait.h>int main(void){ int fd[2]; if (pipe(fd) == -1) { perror("pipe"); return 1; } pid_t pid = fork(); if (pid == 0) { // child: the only reader... who leaves at once close(fd[1]); close(fd[0]); _exit(0); } // The parent still holds BOTH ends here. // TODO: the parent only writes — close the end it does not need wait(NULL); // the reader is gone now printf("Parent: writing into the pipe...\n"); fflush(stdout); const char *msg = "hello?\n"; ssize_t n = write(fd[1], msg, strlen(msg)); printf("Parent: write returned %zd — nobody got killed\n", n); return 0;}
Editing — changes sent to terminal on Run
$ gcc -Wall -o sigpipe sigpipe.c
$ ./sigpipe
Open Full Terminal
Get a Linux terminal with all 13 files from this lesson pre-loaded. Compile, run, and experiment freely.