linux中pipe和dup2详解
2015-11-30 16:13
609 查看
1、什么是管道 管道是半双工的,数据只能向一个方向流动;需要双方通信时,需要建立起两个管道; 只能用于父子进程或者兄弟进程之间(具有亲缘关系的进程); 单独构成一种独立的文件系统:管道对于管道两端的进程而言,就是一个文件,但它不是普通的文件,它不属于某种文件系统,而是自立门户,单独构成一种文件系统,并且只存在于内存中。数据的读出和写入:一个进程向管道中写的内容被管道另一端的进程读出。写入的内容每次都添加在管道缓冲区的末尾,并且每次都是从缓冲区的头部读出数据。2、管道的创建 int pipe(int fd[2]) 该函数创建的管道的两端处于一个中间进程,在实际应用中并没有太大意义,一般在pipe()创建管道后,再fork()一个子进程,然后通过管道实现父子进程之间的通信。3、管道的读写规则 管道两端可分别用描述字fd[0]以及fd[1]来描述,需要注意的是,管道的两端是固定了任务的。即一端只能用于读,由描述字fd[0]表示,称其为管道读端;另一端则只能用于写,由描述字fd[1]来表示,称其为管道写端。4、pipe函数 头文件:#include<unistd.h> 函数原型: int pipe(int fd[2]) 函数参数:fd[2],管道的两个文件描述符,之后就是可以直接操作这两个文件描述符。其中fd[0]为读取端,fd[1]为写入端 返回值:成功返回0,否则返回-1 读fd[0]: close(fd[1]); read(fd[0], buf, BUF_SIZE); 写fd[1]: close(fd[0]); read(fd[1], buf, strlen(buf));5、例子
运行的结果还是一样。只是在36行代码中调用了dup2,把fd[0]复制给newfd。
#include <unistd.h> #include <stdio.h> int main() { int fd[2]; char buf[1024]; pid_t pid; int newfd; if(pipe(fd) != 0) { printf("pipe error\n"); return 0; } pid = fork(); if(pid == -1) { printf("fork error\n"); return 0; } else if(pid > 0) { printf("This is the father process, here write a string to the pipe\n"); char s[] = "Hello! write a string in the father process\n"; close(fd[0]); write(fd[1], s, sizeof(s)); // 向管道中写入数据 } else { printf("This is the child process, here read a string from the pipe\n"); close(fd[1]); dup2(fd[0], newfd); read(newfd, buf, sizeof(buf)); //从管道中读取数据 printf("%s", buf); } waitpid(pid, NULL, 0); return 0; }View Code
运行的结果还是一样。只是在36行代码中调用了dup2,把fd[0]复制给newfd。
相关文章推荐
- Linux下WPS缺失字体
- Centos6.5 安装教程
- linux下的基本操作
- Linux常用命令整理
- linux服务学习之crond
- CentOS 开机自启动脚本
- 在CentOS上安装Java环境:使用yum安装java
- PXE+kickstart安装Linux操作系统
- perl 匹配 Linux grep 出来的结果失败
- CentOS7配置opencv for python (解决问题:[no-member] Module 'cv2' has no 'VideoWriter' member)
- Linux Kernel 2.6进程调度的分析
- linux下用core和gdb查询出现"段错误"的地方
- Ubuntu Linux下设置IP的配置命令
- linux命令--watch,动态监测命令的结果
- Linux命令之trap - 在脚本中处理信号
- linux查看端口是否已开启和查看文件数
- linux的退出问题
- Linux的cron和crontab
- linux 统计grep 后的行数 wc
- linux查看网卡驱动