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]
相关文章推荐
- 一般文件操作(包括管道和套接字)
- 用QSocket来操作Linux命名管道
- linux笔记3(过滤器、管道、常用文件管理操作指令)
- Delphi与管道操作
- pipeExample.c(向管道数据的简单读写操作)
- bobo说shell:shell重定向与管道操作(二)
- linux C++:c++流操作----->rdbuf()
- 2、shell指令操作【ubuntu】 - cp指令如何用管道传参数
- Linux管道操作
- 重定向和管道操作
- LINUX下PHP对命名管道操作权限问题解决小记
- 高级管道操作
- Linux操作之输入输出重定向和管道
- 温故而知新:查看端口占用情况以及DOS中的管道操作/重定向操作
- Win32汇编教程十二 管道操作
- 国际象棋引擎文章(二)匿名管道操作
- python shell脚本(主要讲管道操作的支持)
- 模拟纸牌发送采用不重复的随机数,多线程操作管道流
- linux C++:c++流操作----->rdbuf()
- Java自学--IO操作(3) 管道流