无名管道没有文件名,存在于内存中。当进程结束后,管道也随之结束。
管道的读端是有阻塞的,会等到有数据写入才返回。如果写段关闭,读端会马上返回。
它无法保证数据的原子性。一般用于无名管道一般用于两个进程之间通信。
以下是无名管道代码的基本实现。主要是运用fork()函数诞生子进程,并注意数组元素pipefd[1]写段,pipefd[0]是读端。
pipe必须在fork()之前创建,才能保证亲缘进程使用同一个管道
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
pid_t pid;
int pipefd[2]; //pipe[1]是写入端。pipe[0]是读端
int ret=pipe(pipefd);
if(ret!=0)
{
printf("Create pipe falied!\n");
return -1;
}
pid=fork();
if(pid==0) //子进程
{
write(pipefd[1],"hello world",12);
exit(0);
}
else if(pid>0) //父进程
{
char buffer[12]={0};
read(pipefd[0],buffer,12);
printf("Read data:%s\n",buffer);
wait(NULL); //等待子进程结束
close(pipefd[0]);
close(pipefd[1]);
}
return 0;
}
输出: