匿名管道是父子进程的方法,而有名管道是不同进程的方法,这个“有名”就是mkfifo()函数给的。
先运行写进程,后进行读进程,管道不能进行两边同时进行读写,所以是半双工的。
(匿名管道是内存上的特殊文件,命名管道是硬件上的特殊文件,这个特殊文件进程结束之后打开没有东西,共享文件是硬件上的普通文件,这个文件进程结束之后打开可以看到东西)
写进程代码:
/***************************************************
##filename : namepipeW.c
##author : GYZ
##create time : 2018-10-18 14:14:43
##last modified : 2018-10-18 15:03:39
##description : NA
***************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
int main(int argc,char *argv[])
{
int ret = 0;
char WtoR[] = "frist execute W,next execute R";
ret = mkfifo("./fifo",0666);
if(0 != ret)
{
perror("mkfifo"),exit(-1);
}
printf("%d\n",__LINE__);
ret = open("./fifo",O_WRONLY);
if(0 >= ret)
{
perror("open"),exit(-1);
}
else
{
write(ret,WtoR,sizeof(WtoR));
}
return 0;
}
/***************************************************
##filename : namepipeR.c
##author : GYZ
##create time : 2018-10-18 14:14:43
##last modified : 2018-10-18 15:01:22
##description : NA
***************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
int main(int argc,char *argv[])
{
int ret = 0;
char buf[1024];
memset(buf,0,sizeof(buf));
ret = open("./fifo",O_RDONLY);
if(0 > ret)
{
printf("%d\n",__LINE__);
perror("mkfifo"),exit(-1);
}
else
{
read(ret,buf,sizeof(buf));
printf("read buf is %s\n",buf);
}
close(ret);
return 0;
}