管道
来源:互联网 发布:阳春政府网络问政平台 编辑:程序博客网 时间:2024/06/08 15:15
管道由pipe函数创建,是进程间通信的一种方式。
#include <unistd.h> int pipe(int fd[2]); 返回:成功时为0,出错时为-1
该函数数返回两个文件描述符:fd[0]和fd[1]。前者用于读,后者用于写。
管道的典型用途是提供两个不同进程(一个是父进程,一个是子进程)间的通信手段。 一个管道只能提供单向的数据流,当需要一个双向的数据流时,我们必须创建两个管道,每个方向一个。实际步骤如下:
1.创建管道1(fd1[0]和fd1[1])和管道2(fd2[0]和fd2[1])
2.fork
3.父进程关闭管道1的读端(fd1[0])
4.父进程关闭管道2的写端(fd2[1])
5.子进程关闭管道1的写端(fd1[1)
6.子进程关闭管道2的读端(fd2[0)
实现代码如下:
/* * main.cpp * * Created on: 2013-10-26 * Author: Richard */#include <unistd.h>#include <sys/types.h>#include <sys/wait.h>#include <stdlib.h>#include <stdio.h>#include <string.h>#include <sys/stat.h>#include <fcntl.h>#include <errno.h>void client(int readfd, int writefd){ size_t len; size_t n; char buff[1024]; fgets(buff, 1024, stdin); len = strlen(buff); if (buff[len - 1] == '\n') { len--; } write(writefd, buff, len); while ((n = read(readfd, buff, 1024)) > 0) { write(STDOUT_FILENO, buff, n); }}void server(int readfd, int writefd){ int fd; ssize_t n; char buff[1025]; if ((n = read(readfd, buff, 1024)) == 0) { printf("End of file while reading pathname"); exit(0); } buff[n] = '\0'; if ((fd = open(buff, O_RDONLY)) < 0) { snprintf(buff + n, sizeof(buff) - n, "Cannot open, %s\n", strerror(errno)); n = strlen(buff); write(writefd, buff, n); } else { while ((n = read(fd, buff, 1024)) > 0) { write(writefd, buff, n); } close(fd); }}int main(int argc, char **argv){ int pipe1[2]; int pipe2[2]; pid_t childpid; pipe(pipe1); pipe(pipe2); if ((childpid = fork()) == 0) { close(pipe1[1]); close(pipe2[0]); server(pipe1[0], pipe2[1]); exit(0); } close(pipe1[0]); close(pipe2[1]); client(pipe2[0], pipe1[1]); waitpid(childpid, NULL, 0); return 0;}
main函数创建两个管道并fork一个子进程。客户作为父进程运行,服务器作为子进程运行。第一个管道用于客户向服务器发送路径名,第二个管道用于服务器向客户发送该文件的内容。
- 管道
- 管道
- 管道
- 管道
- 管道
- 管道
- 管道
- 管道
- 管道
- 管道
- 管道
- <>管道
- 管道
- 管道
- 管道
- 管道
- 管道
- |管道
- 计算机网络应用层之cookie
- ognl.MethodFailedException: Method "setPic" failed for object com.employment.action.NewsAction@aac66
- apache 访问权限 小结
- 4.7 可扩展的Listview : ExpandableListView
- android 程序中 经常用到的几种定时器
- 管道
- jQuery 2.0.3 源码分析Sizzle引擎 - 解析原理
- 用java源代码学数据结构<二>: Vector 详解
- 4.8 抽象接口, 回调函数: 短信备份
- 4.9 黑名单数据库的界面展示
- 51系列中data,idata,xdata,pdata的区别
- asp.net最常用的三十三种编程代码
- 4.10 优化LIstView: 在listView中复用历史缓存view对象减少内存开销
- javascript(js)中的 substring和substr方法