您的位置:首页 > 运维架构 > Linux

linux c++ 管道操作

2014-07-16 17:01 190 查看
/*
 * main.cpp
 *
 *  Created on: Jul 16, 2014
 *      Author: john
 */

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<unistd.h>
//read  pipe
void read_from_pipe(int fd)
{
    char message[100]={0};
    read(fd,message,100);
    //for(int i=0;i<100;i++)
    printf("the pipe content is %s\n",message);
}

//write pipe

void write_to_pipe(int fd)
{
    char* msg="the pipe msg";
    write(fd,msg,strlen(msg));
}
 

int main()
{
	int now;
    int fd[2];
    pid_t pid;
     if(pipe(fd))
    {
        printf("create pipe failed\n");
        exit(1); 
     }
    pid=fork();
    switch(pid)
    {
        case -1:
           printf("fork error\n");
           exit(1);
        case 0:
           close(fd[1]);
           read_from_pipe(fd[0]);
           exit(0);
         default:
           close(fd[0]);
           write_to_pipe(fd[1]);
           wait(now);
           exit(0); 
    }
    exit(0);
}

管道,是一种半双工通信方式,也就是说,通信的两方一个只能读,一个只能写,而这是无名管道,所以使用方式只能是在父子进程之间,

管道的一般使用方式是进程在使用fork函数创建子进程先创建一个管道,该管道用于在父子进程之间通信,然后创建子进程,之后父进程,关闭管道的读端,子进程关闭管道的

写端,或者反其道行之

fd[0]是读端 fd[1]是写端

如果某进程要读取管道中的信息那么应该先关闭fd[1],如果要写管道数据则关闭fd[0]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: