您的位置:首页 > 其它

进程间通信-管道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重定向,会将标准输入,输出重定向到管道...

//一个管道的简单例子

#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: