匿名管道是父子程序的方法,而有名管道是不同程序的方法,這個“有名”就是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;
}