1.
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#define FIFO_PATH "/home/gec/my_fifo"
int main()
{
//判断文件是否存在
int access_ret = access(FIFO_PATH, F_OK);
//如果返回值不等于0,就代表文件不存在,就创建
if(access_ret !=0)
{
//1.创建有名管道
int ret = mkfifo(FIFO_PATH, 0777);//1.共享文件夹是创建不了管道文件的,windos是不支持管道文件的
//2.管道文件只能创建在Linux的目录下,建议大家创建在家目录,建议用chmod修改权限
if(-1 == ret)
{
perror("creat fifo failed");
return -1;
}
}
//2.打开管道文件
int fd = open(FIFO_PATH,O_RDONLY);
if(-1 == fd)
{
perror("open fifo failed");
return -1;
}
//3.往管道文件里读
char *buf = malloc(100);
while(1)
{
memset(buf,0,100);
read(fd,buf,100);
printf("jack:%s\n",buf);
if(strcmp(buf ,"byebye\n")==0)
{
break;
}
}
}
2.
#include <sys/stat.h>
#include <stdio.h>
#include <errno.h>
int main()
{
const char *fifo_name = "/tmp/myfifo";
int ret;
// 尝试创建 FIFO
ret = mkfifo(fifo_name, 0777);
if (ret == -1)
{
perror("Failed to create FIFO");
// 这里可以根据错误类型采取不同的措施
return -1;
}
else(ret==0)
{
printf("FIFO created successfully.\n");
return 0;
}
}