Course contentsShow
← C
Lesson 1103 of 1,21915. Systems ProgrammingFree lesson

Closing unused pipe ends

Closing unused pipe ends

What you'll learn: Why and how to close the file descriptors your process doesn't need to prevent deadlocks and resource leaks.

The "Two-Way Street" trap

When you call pipe(), the operating system gives you two file descriptors: one for reading and one for writing. When you then call fork(), the child process inherits copies of both. You now have four active handles to the same pipe.

Think of a pipe like a physical tube. For communication to work clearly, you need a dedicated sender and a dedicated receiver. If everyone holds onto both ends, the "tube" stays open indefinitely, and the OS gets confused about whether anyone is actually finished talking.

Avoiding the infinite wait

The most critical reason to close unused ends is to trigger the End-of-File (EOF) condition.

A process reading from a pipe will wait forever (block) if it thinks more data might arrive. The OS only sends an EOF signal to the reader when all write descriptors for that pipe are closed. If the parent process finishes sending data but the child still has its own copy of the write end open, the child will sit waiting forever to read from itself. It’s like waiting for a phone call while you’re the one holding the receiver off the hook.

Best practice in code

In a standard one-way communication setup, the parent and child should immediately "shut down" the directions they don't intend to use.

int fd[2];
pipe(fd);

if (fork() == 0) {
    // CHILD: I only want to READ
    close(fd[1]); // Close unused write end immediately
    
    char buffer[20];
    read(fd[0], buffer, 20); // This will now receive EOF correctly later
    
    close(fd[0]); // Done reading
} else {
    // PARENT: I only want to WRITE
    close(fd[0]); // Close unused read end immediately
    
    write(fd[1], "Hello Child!", 12);
    
    close(fd[1]); // When I close this, the child finally receives EOF
}

Clean habits, stable systems

Closing unused ends isn't just about avoiding bugs; it's about resource management. Every open file descriptor consumes a slot in the process's file table. In complex systems with many pipes, failing to close unused ends can lead to "file descriptor exhaustion," where your program crashes simply because it ran out of handles. As a rule of thumb: if you aren't using it, close it immediately after the fork().

Key takeaway

Always close the unused ends of a pipe in both the parent and child to ensure EOF signals are sent correctly and to prevent processes from hanging.