Linux 拨号vps windows公众号手机端

C++中如何使用管道实现进程间通信

lewis 7年前 (2018-03-22) 阅读数 8 #程序编程
文章标签 c++

在C++中使用管道实现进程间通信可以通过以下步骤:

  1. 包含相关的头文件:
#include <iostream>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
  1. 创建管道:
int fd[2];
if (pipe(fd) < 0) {
    std::cerr << "Error creating pipe" << std::endl;
    return 1;
}
  1. 创建子进程并进行通信:
pid_t pid = fork();
if (pid < 0) {
    std::cerr << "Error forking" << std::endl;
    return 1;
} else if (pid == 0) {
    // 子进程
    close(fd[0]); // 关闭读端
    char message[] = "Hello, parent!";
    write(fd[1], message, strlen(message) + 1);
    close(fd[1]); // 关闭写端
} else {
    // 父进程
    close(fd[1]); // 关闭写端
    char message[100];
    read(fd[0], message, sizeof(message));
    std::cout << "Received message from child: " << message << std::endl;
    close(fd[0]); // 关闭读端
}

在这个例子中,父进程创建了一个管道,并通过fork()函数创建了一个子进程。子进程向管道中写入了一条消息,父进程从管道中读取了这条消息并输出到控制台。最后记得关闭管道的读写端来释放资源。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门