Pipe, IPC Mechanisms

POSIX Pipe

Anonymous Pipes

Anonymous pipes can be used for communication between parent and child processes on the same machine. In C++, anonymous pipes can be created using the pipe() system call on POSIX systems or CreatePipe() on Windows.

Example on POSIX systems:

#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
 
int main() {
    int pipe_fd[2];
    pipe(pipe_fd);  // Create a pipe
 
    pid_t pid = fork();  // Fork a child process
    if (pid == 0) {
        // Child process
        close(pipe_fd[1]);  // Close write end
        char buffer[128];
        read(pipe_fd[0], buffer, sizeof(buffer));
        std::cout << "Child received: " << buffer << std::endl;
        close(pipe_fd[0]);
    } else {
        // Parent process
        close(pipe_fd[0]);  // Close read end
        const char *msg = "Hello from parent!";
        write(pipe_fd[1], msg, strlen(msg) + 1);
        close(pipe_fd[1]);
        wait(NULL);  // Wait for child to finish
    }
 
    return 0;
}

In this example, an anonymous pipe is used for communication between a parent and a child process.

Named Pipes (FIFO)

Named pipes (also called FIFOs) allow unrelated processes to communicate, and can persist beyond the lifetime of the process. They are useful when you want to establish communication between processes that do not have a parent-child relationship.

Example on POSIX systems:

#include <iostream>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
 
int main() {
    const char *fifo_path = "/tmp/my_fifo";
    mkfifo(fifo_path, 0666);
 
    if (fork() == 0) {
        // Child process
        int fd = open(fifo_path, O_RDONLY);
        char buffer[128];
        read(fd, buffer, sizeof(buffer));
        std::cout << "Child received: " << buffer << std::endl;
        close(fd);
    } else {
        // Parent process
        int fd = open(fifo_path, O_WRONLY);
        const char *msg = "Hello from parent!";
        write(fd, msg, strlen(msg) + 1);
        close(fd);
        wait(NULL);  // Wait for child to finish
    }
 
    unlink(fifo_path);  // Remove the FIFO
    return 0;
}

This example uses a named pipe (FIFO) to allow two processes to communicate.