linux管道程序,linux c++ 管道操作

/*

* main.cpp

*

* Created on: Jul 16, 2014

* Author: john

*/

#include

#include

#include

#include

#include

//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]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值