无名管道
无名管道和有名管道是Linux系统内核的特殊文件,用于进程之间的通信。
无名管道相当于一个队列结构,fd[1]为写入端(入队),fd[0]为读出端(出队)。其中信息读出后即删除,再次读取时即为下一个信息。
头文件
#include <unistd.h>
函数原型
int pipe(int pipefd[2]);
功能:创建无名管道文件。无名管道是一个特殊文件,不可由open函数创建。
参数:fd[2]有两个成员 fd[0]和 fd[1],他们都是文件描述符。 管道有固定的读端 fd[0]和固定的写端 fd[1]。
返回值:成功返回 0,出错返回-1
1.管道是创建在内存中,进程结束空间释放,管道不复存在。
2.无名管道和有名管道都是半双工通信,实现双向通信需要建立两个管道。
3.无名管道是linux特殊文件,不能在与windows共享的文件夹中创建。
4.无名管道只用于父子进程之间,有名管道可用于无亲缘关系的进程之间。
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
int main()
{
int fd[2];
int pid;
char buf[128];
// int pipe(int pipefd[2]);
if(pipe(fd)==-1){
printf("creat pipe failed\n");
}
pid=fork();
if(pid<0){
printf("creat child failed\n");
}
else if(pid>0){
sleep(3);
printf("this is father\n");
close(fd[0]);
write(fd[1],"hello from father",strlen("hello from father"));
wait(NULL);
}
else{
printf("this is child\n");
close(fd[1]);
read(fd[0],buf,128);
printf("read from father:%s\n",buf);
exit(0);
}
return 0;
}