c/c++ 里的进程间通信 , 管道 pipe 编程举例

(1)以下是一个网上的使用 pipe 编程的范例:

c 复制代码
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>

int main() {
    int pipefd[2];
    pid_t pid;
    char writeMsg[] = "Hello from parent process!";
    char readMsg[100];

    // 创建管道
    if (pipe(pipefd) == -1) {
        perror("pipe");
        exit(EXIT_FAILURE);
    }

    // 创建子进程
    pid = fork();
    if (pid == -1) {
        perror("fork");
        exit(EXIT_FAILURE);
    }

    if (pid > 0) { // 父进程
        close(pipefd[0]); // 关闭读取端

        // 向管道写入消息
        write(pipefd[1], writeMsg, strlen(writeMsg) + 1); // +1 是为了包含终止符 '\0'
        close(pipefd[1]); // 写入完成后关闭写入端

        wait(NULL);       // 等待子进程结束
    }
     else  { // 子进程
        close(pipefd[1]); // 关闭写入端

        // 从管道读取消息
        ssize_t numBytes = read(pipefd[0], readMsg, sizeof(readMsg) - 1);
        if (numBytes == -1) {
            perror("read");
            exit(EXIT_FAILURE);
        }
        readMsg[numBytes] = '\0'; // 添加字符串终止符

        // 打印读取的消息
        printf("Received message: %s\n", readMsg);
        close(pipefd[0]); // 读取完成后关闭读取端
    }

    return 0;
}

(2)上面引用了 wait() 函数,给出其定义:

(3)再给出 linux 0.11 里很重要的管道文件的创建源码:

(4)文件都对应 inode 节点,接着给出文件描述符 ,file 文件结构 ,inode 节点结构的定义与关联关系:

(5)读写管道,主要依赖于 linux 0.11 系统的这俩系统函数:

(6)给出我自己的简单版的 实验结果:

(7)

谢谢

相关推荐
香蕉卜拿拿拿2 小时前
软件解耦与扩展的利器:基于C++与C#的插件式开发实践
c++
CoderCodingNo3 小时前
【GESP】C++五级真题(贪心和剪枝思想) luogu-B3930 [GESP202312 五级] 烹饪问题
开发语言·c++·剪枝
永远前进不waiting4 小时前
C复习——1
c语言·开发语言
阿闽ooo4 小时前
深入浅出适配器模式:从跨国插头适配看接口兼容的艺术
c++·设计模式·适配器模式
一路往蓝-Anbo4 小时前
【第13期】中断机制详解 :从向量表到ISR
c语言·开发语言·stm32·单片机·嵌入式硬件
oioihoii6 小时前
跨越进程的对话之从管道到gRPC的通信技术演进
c++
爱装代码的小瓶子7 小时前
算法【c++】二叉树搜索树转换成排序双向链表
c++·算法·链表
阳洞洞7 小时前
cmake中如何从include_directories中移除某个特定的头文件
c++·cmake
墨雪不会编程7 小时前
C++【string篇1遍历方式】:从零开始到熟悉使用string类
java·开发语言·c++
JAY_LIN——88 小时前
C语言>字符 (strlen) | 字符串函数(strcpy、strcat)
c语言