linux c++ 管道操作

来源:互联网 发布:淘宝店铺月销量怎么看 编辑:程序博客网 时间:2024/06/07 23:48
/* * 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  pipevoid 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 pipevoid 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]

0 0
原创粉丝点击