1.只读 open 要阻塞的代码:
#include<stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include<errno.h>
#include<fcntl.h>
int main()
{
//int mkfifo(const char *pathname, mode_t mode);
if( (mkfifo("./file",0600) == -1) && errno != EEXIST)
{
printf("mkfifo fialed\n");
perror("why");
}
open("./file",O_RDONLY);
printf("open success\n");
return 0;
}
运行结果:
2.实现简单通信代码
(1)读取数据的代码:
#include<stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include<errno.h>
#include<fcntl.h>
int main()
{
//int mkfifo(const char *pathname, mode_t mode);
if( (mkfifo("./file",0600) == -1) && errno != EEXIST)
{
printf("mkfifo fialed\n");
perror("why");
}
open("./file",O_RDONLY); //O_RDONLY 是以读打开FIFO
printf("open success\n");
return 0;
}
(2)写入数据的代码:
#include<stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include<errno.h>
#include<fcntl.h>
int main()
{
open("./file",O_WRONLY); //O_WRONLY是以写打开一个FIFO
printf("write open success\n");
return 0;
}
运行结果:
3.通信代码
(1)读取数据的代码:
read.c
#include<stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include<errno.h>
#include<fcntl.h>
int main()
{
//int mkfifo(const char *pathname, mode_t mode);
char buf[30] = {0};
if( (mkfifo("./file",0600) == -1) && errno != EEXIST)
{
printf("mkfifo fialed\n");
perror("why");
}
int fd = open("./file",O_RDONLY);
printf("open success\n");
int n_read = read(fd,buf,30);
printf("read %d byte form fifo,context:%s\n",n_read,buf);
close(fd);
return 0;
}
编译:gcc read.c -o read
(2)写入数据的代码:
write.c
#include<stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include<errno.h>
#include<fcntl.h>
#include<string.h>
int main()
{
char* str = "message form fifo";
int fd = open("./file",O_WRONLY);
printf("write open success\n");
write(fd,str,strlen(str));
close(fd);
return 0;
}
编译:gcc write.c -o write
(3)运行代码实现通信流程:
先运行:./read
再运行: ./write
(4)运行结果: