Fundamentals 8 min read

Master Linux Pipes and FIFOs: Build a Simple C Chat Application

This article explains the concepts of anonymous and named pipes in Linux, compares their characteristics, shows how to create them with mknod and mkfifo, and provides a complete C example that implements a two‑process chat program using threads and pipe I/O.

ITPUB
ITPUB
ITPUB
Master Linux Pipes and FIFOs: Build a Simple C Chat Application

What is a Pipe?

A pipe is a unidirectional communication mechanism between two processes, also called a half‑duplex pipe. In Linux it is one of the earliest Unix IPC forms. Data flows from a writer to a reader; for full‑duplex communication you need two pipes. Pipes can only be used between related processes (parent‑child or siblings).

Anonymous Pipe Basics

When a pipe is created, the kernel returns a pair of file descriptors stored in an array int pipefd[2]. pipefd[0] is the read end, pipefd[1] is the write end. The pipe exists only in memory and disappears when the processes close the descriptors.

#include <unistd.h>
int pipe(int pipefd[2]);

Typical usage: a process calls pipe(), then fork() a child. The parent writes to pipefd[1], the child reads from pipefd[0]. Because the pipe is anonymous, both ends must belong to processes that share a common ancestor.

Named Pipes (FIFOs)

Named pipes overcome the ancestry limitation by existing as a special file in the filesystem. They are created with a pathname and can be opened by any process that has permission to that path. FIFO semantics follow a first‑in‑first‑out order.

Two system calls are used to create a FIFO:

int mknod(const char *pathname, mode_t mode, dev_t dev);
int mkfifo(const char *pathname, mode_t mode);

Both return 0 on success, -1 on failure.

Creating a FIFO

Example code:

#include <sys/types.h>
#include <sys/stat.h>
int mknod(const char *pathname, mode_t mode, dev_t dev);
int mkfifo(const char *pathname, mode_t mode);

if (mkfifo(FIFO_WRITE, S_IFIFO | 0666) != 0) {
    printf("Can't create FIFO %s because %s
", FIFO_WRITE, strerror(errno));
    exit(1);
}

Chat Program Using a Named Pipe

The following C program demonstrates a simple two‑process chat using a FIFO. One thread reads from the FIFO, the other writes user input to it. The program uses pthread for concurrency.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <pthread.h>

#define FIFO_READ  "readfifo"
#define FIFO_WRITE "writefifo"
#define BUF_SIZE   1024

int left = 0;

void *read_buf() {
    int rfd = -1;
    char buf[BUF_SIZE] = {0};
    int i;
    printf("等待对方……
");
    while ((rfd = open(FIFO_READ, O_RDONLY)) == -1) {
        sleep(1);
    }
    while (left != 1) {
        int len = read(rfd, buf, BUF_SIZE);
        if (len > 0) {
            buf[len] = '\0';
            if (strcmp(buf, "不理你了") == 0) {
                printf("
对方已经走开!
");
                left = 1;
                break;
            }
            printf("对方:%s
", buf);
            printf("我:");
            fflush(stdout);
        }
    }
    close(rfd);
    return NULL;
}

void *write_to() {
    int wfd;
    char buf[BUF_SIZE];
    umask(0);
    if (mkfifo(FIFO_WRITE, S_IFIFO | 0666) != 0) {
        printf("Can't create FIFO %s because %s
", FIFO_WRITE, strerror(errno));
        exit(1);
    }
    wfd = open(FIFO_WRITE, O_WRONLY);
    if (wfd == -1) {
        printf("open FIFO %s error: %s
", FIFO_WRITE, strerror(errno));
        exit(1);
    }
    while (left != 1) {
        printf("我: ");
        fgets(buf, BUF_SIZE, stdin);
        buf[strlen(buf)-1] = '\0';
        if (strcmp(buf, "不理你了") == 0 || left == 1) {
            break;
        }
        write(wfd, buf, strlen(buf));
        close(wfd);
        unlink(FIFO_WRITE);
        exit(0);
    }
    return NULL;
}

int main(int argc, char *argv[]) {
    pthread_t thIDr, thIDw;
    pthread_create(&thIDr, NULL, (void *)read_buf, NULL);
    pthread_create(&thIDw, NULL, (void *)write_to, NULL);
    pthread_join(thIDr, NULL);
    pthread_join(thIDw, NULL);
    return 0;
}

Running the program in two terminals (one as the reader, the other as the writer) produces a simple chat interface. The output screenshot is shown below.

Key Takeaways

Anonymous pipes are limited to related processes; named pipes (FIFOs) remove this restriction.

Use mkfifo or mknod to create a FIFO file, then open it with standard file‑descriptor calls.

Combining FIFOs with threads allows building simple inter‑process chat tools in C.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

CIPCFIFOpipesnamed pipeschat program
ITPUB
Written by

ITPUB

Official ITPUB account sharing technical insights, community news, and exciting events.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.