进程间通信-管道pipe
2014-03-24 21:33
211 查看
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重定向,会将标准输入,输出重定向到管道...
//一个管道的简单例子
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 10 int 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 write int 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; }
相关文章推荐
- Linux进程间通信之管道(pipe)、命名管道(FIFO)与信号(Signal)
- Linux进程间通信之管道(pipe)、命名管道(FIFO)与信号(Signal)
- Linux进程间通信之管道(pipe)、命名管道(FIFO)与信号(Signal)
- Linux进程间通信(三):匿名管道 popen()、pclose()、pipe()、close()、dup()、dup2()
- Windows API 进程间通信,管道(Pipe)
- 进程间通信---------有名管道(named pipe/FIFO)
- Linux--进程间通信(一)-管道(pipe)通信
- Linux进程间通信——管道(pipe)与命名管道(FIFO)
- Linux环境进程间通信(一)——管道(pipe)和命名管道(fifo)
- 进程间通信(4) - 管道(pipe)
- Linux--进程间通信(二)-命名管道(pipe)通信
- Linux进程间通信之管道(pipe)、命名管道(FIFO)与信号(Signal)
- WINDOWS API 进程间通信,管道(PIPE),Remoting技术
- Linux环境进程间通信(一)——管道(pipe)和命名管道(fifo)
- Pipe,利用匿名管道实现进程间通信
- Linux系统编程——进程间通信:管道(pipe)
- Linux 进程间通信之管道(pipe),(fifo)
- Linux系统编程——进程间通信:管道(pipe)
- 进程间通信---匿名管道pipe
- Linux环境进程间通信 --- 管道Pipe