linux进程间通讯--管道

/*************************************************************************
    > 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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值