目录
两者区别
无名管道:
① 无文件节点,不存在文件。
② 只能用于具有亲缘关系的进程间通信(父子进程,兄弟进程.......)。
③ 有固定的读端和写端。
④ 通过pipe创建无名管道得到描述符fd[0]:读,fd[1]:写进行通信。
有名管道:
① 有文件节点,存在文件(p 管道文件),文件只有id号,不占磁盘空间
② 可以使互不相同的两个进程实现彼此通信。
③ 通过mkfifo创建管道文件,通过open打开文件进行进程间通信。
无名管道
函数:pipe
函数原型:int pipe(int fd[2]);
头文件:#include <unistd.h>
函数功能:创建无名管道(内核中临时缓存空间)
得到两个文件描述符 fd[0]:读 fd[1]:写
返回值:成功返回0,失败返回-1
无名管道自己通信
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
int fd[2] = {0};
char buf[128] = {0};
int res = pipe(fd);//创建无名管道
if(res == -1)
{
perror("pipe");
exit(-1);
}
printf("fd[0]:%d\n",fd[0]);
printf("fd[1]:%d\n",fd[1]);
write(fd[1],"hello",5);
read(fd[0],buf,127);//当管道没有内容会读阻塞。
printf("buf:%s\n",buf);
//关闭
close(fd[0]);
close(fd[1]);
return 0;
}
无名管道父子进程间通信
需先创建管道再创建进程
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
int fd[2] = {0};
char buf[128] = {0};
int res = pipe(fd); //创建无名管道
if (res == -1)
{
perror("pipe");
exit(-1);
}
printf("fd[0]:%d\n", fd[0]);
printf("fd[1]:%d\n", fd[1]);
int sid = fork(); //要先创建无名管道再创建进程
if (res == -1)
{
perror("fork");
exit(-1);
}
if (sid == 0) //子进程
{
close(fd[0]);
write(fd[1], "hello", 5);
close(fd[1]);
exit(0);
}
else //父进程
{
close(fd[1]);
read(fd[0], buf, 127); //当管道没有内容会读阻塞。
printf("fubuf:%s\n", buf);
close(fd[0]);
}
return 0;
}
有名管道
函数:mkfifo
函数原型:int mkfifo(const char *filename, mode_t mode)
头文件:#include <sys/types.h> #include <sys/state.h>
参数: 1)filename:要创建的管道名
2)mode:管道的访问权限 (如 :0666)
返回值:成功0,出错-1;
有名管道的写端
open打开的时候要可读可写,管道才通,不然会一直堵塞
若FIFO空间不足,进程会阻塞,直到数据都写入为止
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
int main()
{
mkfifo("./pipename",0666);
printf("创建管道成功\n");
int fd = open("./pipename",O_RDWR);//要可读可写才通,不然会一直堵塞
write(fd,"hello",5);
printf("写入管道成功\n");
close(fd);
return 0;
}
有名管道的读端
缺省情况,如果当FIFO内没有数据,读进程将一直阻塞到有数据写入或FIFO写端都关闭
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
int main()
{
char buf[128] = {0};
int fd = open("./pipename",O_RDONLY);
read(fd,buf,127);
printf("%s\n",buf);
printf("读取成功\n");
close(fd);
return 0;
}