两个子进程之间使用命名pipe
两个子进程间可以使用命名管道,非常简单。管道如果文件一样存在硬盘中,使用ls可以查看,管道文件0字节。使用fork函数分别创建两个子进程。
一个负责读数据,一个负责写数据。
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/wait.h>#define FIFO_PATH "./fifo_fork_demo"
#define MSG "Hello from child writer!\n"int main(void)
{/* 1. 创建有名管道 ----------------------------------------------------- */if (mkfifo(FIFO_PATH, 0666) == -1) {perror("mkfifo");return 1;}/* 2. fork 两个子进程 --------------------------------------------------- */pid_t writer_pid = fork();if (writer_pid == 0) { /* 子进程 A:写 */int fd = open(FIFO_PATH, O_WRONLY); /* 阻塞到有读端 */if (fd == -1) { perror("open writer"); _exit(1); }write(fd, MSG, sizeof(MSG));close(fd);_exit(0);}pid_t reader_pid = fork();if (reader_pid == 0) { /* 子进程 B:读 */int fd = open(FIFO_PATH, O_RDONLY); /* 阻塞到有写端 */if (fd == -1) { perror("open reader"); _exit(1); }char buf[64];ssize_t n = read(fd, buf, sizeof(buf) - 1);if (n > 0) {buf[n] = '\0';printf("reader child got: %s", buf);}close(fd);_exit(0);}/* 3. 父进程等待两个子进程结束 ----------------------------------------- */int st;waitpid(writer_pid, &st, 0);waitpid(reader_pid, &st, 0);/* 4. 清理 FIFO --------------------------------------------------------- */unlink(FIFO_PATH);puts("parent: all children finished, fifo removed.");return 0;
}