/*************************************************************************
> File Name: linux_pipe.cpp
> Author: lijun
> Mail: 2291042162@qq.com
> Created Time: 2017年08月29日 星期二 16时03分08秒
************************************************************************/
//对于管道 linux上常见的就是 ls -l | grep strings 这里的|就是一个管道
//通过ls -l 进程的输出输入管道然后输出给grep进程作为输入
#include<iostream>
#include<unistd.h>
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
using namespace std;
//匿名管道只能用在父子进程中,通过fork实现
//有两种形式 1:popen 2:pipe
//其中popen 基于文件流 其实就是和fopen函数一样 而且读取用的也是fread fwrite
//pipe则是通过文件描述符(两个 0表示只读 1表示只写) 而且读取方式为read write
void test_AnonymousPipe()
{
char * strTest = "hello AnonymousPipe";
int iFileDes[2]={0};
pid_t pid;
if(pipe(iFileDes)==0)
{
pid = fork();
if(pid ==-1)//
{
printf("fork failed");
}
else if(pid == 0)//子进程
{
const int ciBufLen = 64;
char cBuffer[ciBufLen]={0};
read(iFileDes[0],cBuffer,ciBufLen);
printf("the child process received :%s\n",cBuffer);
exit(0);
}
else//父进程
{
write(iFileDes[1],strTest,strlen(strTest));
printf("the parent process send :%s\n",strTest);
sleep(2);
}
}
}
//命名管道则可以用在不同本机进程中,但是为了方便演示,本例依然采用父子进程
//命名管道使用mkfifo创建一个管道(仅仅是创建)
//命名管道也是采用open 的方式打开一个管道 然后依然是read write 进行读写
//看上去跟匿名管道的popen 很像
void test_NamePipe()
{
const char * chFifoName = "/tmp/test_NamePipe";
const char * strTest = "hello NamePipe";
int iPipeId = -1;
if(access(chFifoName,F_OK) == -1)
{
int res = mkfifo(chFifoName,0777);
if(res != 0)
{
printf("create fifo failed\n");
return;
}
}
pid_t pid = fork();
if(pid == -1)
{
printf("fork failed\n");
}
else if(pid == 0)
{
const int ciBufLen = 64;
char chBuffer[ciBufLen]={0};
iPipeId = open(chFifoName,O_RDONLY);
read(iPipeId,chBuffer,ciBufLen);
printf("the child process received :%s\n",chBuffer);
close(iPipeId);
exit(0);
}
else
{
iPipeId = open(chFifoName,O_WRONLY);
write(iPipeId,strTest,strlen(strTest));
printf("the parent process send :%s\n",strTest);
sleep(2);
close(iPipeId);
}
}
int main()
{
test_AnonymousPipe();
test_NamePipe();
return 0;
}
linux进程间通讯--管道
最新推荐文章于 2024-01-07 14:19:13 发布