父子进程可以通过管道进行数据交互,一个管道只能有一个数据流向,要实现双工通信,可以使用两个管道实现。
管道工作原理:
数据交互图:
单工通信代码实现:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <iostream>
using namespace std;
const int MAX_BUFFSIZE = 1024;
int main()
{
int pipe_fd[2];
pid_t pid;
char buff[MAX_BUFFSIZE];
memset(buff,'\0',sizeof(buff));
if (pipe(pipe_fd) < 0)
{
cout<<"pipe create error";
}
if ((pid = fork()) < 0)
{
cout<<"fork error";
}
if (pid > 0)
{
close(pipe_fd[0]);
cin>>buff;
write(pipe_fd[1],buff,sizeof(buff));
}
if (pid == 0)
{
close(pipe_fd[1]);
if ((read(pipe_fd[0],buff,MAX_BUFFSIZE)) > 0)
{
cout<<"Msg from parent:"<<buff;
}
}
return 0;
}
测试结果: