APUE学习之----进程通信pipe实现管道
2015-12-07 14:49
381 查看
一,pipe()介绍
管道的特点:
1.管道是半双工的,即同一时间数据只能从一端流向另一端。试想,如果一个管道从两边同时输入和输出数据,那么管道里的数据就乱了。
2.管道的两端一端作为读端,一端作为写端。
3.管道具有自适应的特点,默认会适应速度比较慢的一方,管道被写满或读空时速度快的一方会自动阻塞。
pipe(2) 用于创建管道,pipefd 是一个数组,表示管道的两端文件描述符,pipefd[0] 端作为读端,pipefd[1] 端作为写端。
pipe(2) 产生的是匿名管道,在磁盘的任何位置上找不到这个管道文件,而且匿名管道只能用于具有亲缘关系的进程之间通信。
一般情况有亲缘关系的进程之间使用管道进行通信时,会把自己不用的一端文件描述符关闭。
下面用两个pipe()管道实现父进程和子进程之间的互相传送数据。
二,代码实现
其中pa_write用于父进程向子进程发送数据,pa_read用于父进程读取子进程发送的数据。
管道的特点:
1.管道是半双工的,即同一时间数据只能从一端流向另一端。试想,如果一个管道从两边同时输入和输出数据,那么管道里的数据就乱了。
2.管道的两端一端作为读端,一端作为写端。
3.管道具有自适应的特点,默认会适应速度比较慢的一方,管道被写满或读空时速度快的一方会自动阻塞。
#include <unistd.h> int pipe(int pipefd[2]);
pipe(2) 用于创建管道,pipefd 是一个数组,表示管道的两端文件描述符,pipefd[0] 端作为读端,pipefd[1] 端作为写端。
pipe(2) 产生的是匿名管道,在磁盘的任何位置上找不到这个管道文件,而且匿名管道只能用于具有亲缘关系的进程之间通信。
一般情况有亲缘关系的进程之间使用管道进行通信时,会把自己不用的一端文件描述符关闭。
下面用两个pipe()管道实现父进程和子进程之间的互相传送数据。
二,代码实现
其中pa_write用于父进程向子进程发送数据,pa_read用于父进程读取子进程发送的数据。
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> int main(int argc,char *argv[]) { int pa_write[2],pa_read[2]; pid_t pid; int len; char buf[BUFSIZ]; if(pipe(pa_write)<0){ perror("pipe()"); exit(1); } if(pipe(pa_read)<0){ perror("pipe()"); exit(1); } pid=fork(); if(pid<0){ perror("fork()"); exit(1); } else if(pid==0){ close(pa_write[1]); close(pa_read[0]); printf("BUFSIZ:%d\n",BUFSIZ); len=read(pa_write[0],buf,BUFSIZ); printf("child output:%s\n",buf); write(pa_read[1],"hello,how are you",17); close(pa_read[1]); close(pa_write[0]); exit(0); } else{ close(pa_write[0]); write(pa_write[1],"hello zt",8); sleep(1); len=read(pa_read[0],buf,BUFSIZ); printf("parent output:%s\n",buf); close(pa_read[0]); close(pa_write[1]); wait(NULL); exit(0); } }
相关文章推荐
- 队列ArrayBlockingQueue的使用
- 偶然翻出很久很久以前写的一款sqlmap UI,有点年头了
- 基于jQuey实现鼠标滑过变色(整行变色)
- django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE的解决办法
- UI控件-UITextField
- [DP] Unique Binary Search Trees
- UICollectionView关于item的报错
- 270. Closest Binary Search Tree Value
- UIView的hitTest:方法和pointInside:方法的实现
- 顺序容器Vector,List,,Deque区别
- UIImageView-播放序列图(简单的动画效果实现)
- 容器(三):队列容器Deque
- configure.in:18: required file `build/ltmain.sh' not found
- jsp Request获取url信息的各种方法比较
- heat template: get_param to get value from JSON param.
- easyui 获得父级tabs跳转
- 使用 CreateTimerQueueTimer 定时器时需要注意的一个参数
- iOS--- UITableView + UISearchDisplayController - - - - -实现搜索功能
- iOS中UITextField、UITextView的字数限制
- JUint测试出现的问题