linux 管道
2014-04-10 20:27
260 查看
#include <unistd.h> #include <sys/types.h> #include <stdio.h> #include <stdlib.h> #include <string.h> //管道通讯:单向,先进先出,管道尾部写入数据,管道头部读出数据;数据读出后,管道将自动删除该数据; //无名管道,用于父子进程间通讯,先创建管道,再fork创建子进程,该子进程继承父进程创建的管道; // 管道创建 int pipe(int filedis[2]); 管道关闭close(filedis[2]); int main() { int pipe_fd[2]; pid_t pid; char buf[100]; int readnum,writenum; memset(buf,0,100);//清buf if(pipe(pipe_fd)<0) { printf("creat pipe failure!\n"); exit(1); } else printf("creat pipe success!\n"); if((pid=fork())==0)//子进程 { close(pipe_fd[1]);//关闭管道尾部(管道写) if((readnum=read(pipe_fd[0],&buf,6))>0) printf("read pipe success,number=%d,data=%s\n",readnum,buf); else if(readnum==0) printf("pipe is empty!\n"); else printf("read pipe failure!\n"); if((readnum=read(pipe_fd[0],&buf,15))>0) printf("read pipe success,number=%d,data=%s\n",readnum,buf); else if(readnum==0) printf("pipe is empty!\n"); else printf("read pipe failure!\n"); close(pipe_fd[0]);//关闭管道头部,管道读结束 exit(0); } else if(pid>0) { close(pipe_fd[0]);//关闭管道头部(管道读) if((writenum=write(pipe_fd[1],"delta electronic ",17))>0) printf("write pipe success!,number=%d,data=%s\n",writenum,"delta electronic "); else printf("write pipe failure!\n"); if((writenum=write(pipe_fd[1],"will",4))>0) printf("write pipe success!,number=%d,data=%s\n",writenum,"will"); else printf("write pipe failure!\n"); close(pipe_fd[1]);//关闭管道尾部,管道写结束 waitpid(pid,NULL,0);//等待子进程结束 exit(0); } exit(0); }
相关文章推荐
- Linux管道和过滤器
- linux进程间通信之管道
- Linux操作系统分析(10) - 进程通信之管道与信号量
- Linux管道的实现机制
- UNIX/Linux进程间通信IPC---管道--全总结(实例入门)
- Linux下的有名管道(03)---使用函数创建和删除有名管道
- linux学习——管道
- Linux 进程间通讯之创建无名管道和读写无名管道
- 探索linux管道的容量
- 老大让我学Linux之管道
- linux 中 xargs、cut 以及管道综合应用
- Linux下的管道编程技术
- Linux匿名管道和命名管道模拟实现
- 【Linux】进程间通信-命名管道FIFO
- linux目录介绍 归档 管道符的管理和应用
- Linux目录结构、bash的基础特性、I/O重定向及管道
- Linux进程间的通信——有名管道fifo与守护进程deamon
- 学习笔记☞Linux常用命令【三】 ( 简单shell编程,管道,重定向,输出,进程,网络管理,关机重启)
- Linux_ pipe 匿名管道demo
- Linux - 进程间通信 - 匿名管道