进程间通信-管道pipe
来源:互联网 发布:淘宝新手怎么找供货商 编辑:程序博客网 时间:2024/05/17 22:36
pipe是进程间通信的一种方式,它有两个限制条件
1、只能在具有公共祖先的进程之间使用,通常用于父子进程之间通信
2、它半双工的,即一个进程不能同时读和写
尽管如此,pipe仍然是最常用的进程间通信方式
创建管道用pipe函数
int pipe(int filedes[2])
filedes[0] 是管道的读描述符
filedes[1]是管道的写描述符
返回值:成功返回0,失败返回-1
pipe必须在调用fork之前创建,这样父子进程才能共享文件这个管道。
pipe的读写:与普通文件的读写一样,用read和write函数
当所有数据被读取后。read返回0,表示到了文件末尾,注意当管道的写端还有进程时,就不会产生文件结束标志。那么read将一直阻塞直到有数据可读
如果写一个读端已被关闭的管道,将会出错,产生SIGPIPE信号,write返回-1
当用pipe进行进程将通信的时候,通常会涉及到IO重定向,会将标准输入,输出重定向到管道...
//一个管道的简单例子
#include<stdio.h>#include<unistd.h>#include<stdlib.h>#include<string.h>#define BUFLEN 10int main(int argc, char *arg[]){int fd[2]; char line[BUFLEN];pid_t pid; int n;if(pipe(fd) < 0) //创建管道{perror("pipe:");exit(1);}if((pid = fork()) < 0){perror("fork");}else if(pid == 0){close(fd[1]); // close writeint count = 0;while((n = read(fd[0],line+ count ,BUFLEN)) > 0) //一口气把数据读完{count += n;printf("n = %d\n",n);}line[count] = '\0';printf("length = %d\n",strlen(line));printf("from parent:%s\n",line);printf("read finish\n");}else{close(fd[0]);scanf("%s",line);write(fd[1],line,strlen(line));close(fd[1]); //这里一定要关闭,否则子进程中的read会一直阻塞,因为他没有收到文件结束符}printf("wait for child\n");wait(NULL);return 0;}
0 0
- 进程间通信-管道pipe
- 进程间通信 管道pipe
- 进程间通信--管道(pipe)
- 进程通信----管道(pipe)
- 进程间通信——管道(Pipe)
- 运用管道(pipe)进行进程间通信
- Windows API 进程间通信,管道(Pipe)
- 管道-pipe函数 进程间通信
- 进程间通信---匿名管道pipe
- Linux进程间通信之管道(pipe)
- Linux环境进程间通信 --- 管道Pipe
- Windows API 进程间通信,管道(Pipe)
- 进程间通信之管道pipe
- Linux 进程间管道pipe通信
- Windows API 进程间通信,管道(Pipe)
- 进程间通信(4) - 管道(pipe)
- 进程间通信:管道(pipe)
- 进程间通信-管道 IPC pipe
- 自定义的时钟,DatePickerDialog 和 TimePickerDialog的使用
- 题目:剔除一个字符中重复的字符,然后按ASCII码值从小到大排列。 例如,输入:abbcccddeeeffgghh 输出:abcdefgh 注意:1、剔除是整个字符串中重复的字符,而不是连续的字符 2
- Edit Distance
- 数据库中的事务、存储过程和触发器的简单使用
- JS实现图片滚动效果
- 进程间通信-管道pipe
- code forces 3A Shortest path of the king
- arcgis api for flex之一、初学问题解决
- ViewFlipper
- openssl多线程实例
- 三层架构——系统登录
- Uva 10791 - Minimum Sum LCM 解题报告(因式分解)
- 转换MFC文件打不开
- 堆排序之MAX-HEAPIFY注释