如何在C中制作一个fifo特殊文件?
How to make a fifo special file in C?
我必须在 Ubuntu 的 C 程序中使用 mkfifo
。但是当我 运行 代码时出现错误:no such file or directory
.
我觉得问题是因为我没有设置panel_fifo
环境变量。但是我不知道我该怎么做。
这是我用来测试此方法的代码:
char *myfifo="./sock/myfifo";
if (mkfifo(myfifo,0777)<0)
perror("can't make it");
if (fd=open(myfifo,O_WRONLY)<0)
perror("can't open it");
我编译这个:
gcc gh.c -o gh
当我 运行 时,我收到此错误消息:
can't make it:no such file or directory
can't open it:no such file or directory
有关创建目录路径的通用 C(和 C++)解决方案,请参阅 How can I create a directory tree in C++/Linux。对于眼前的问题,这是矫枉过正,直接调用 mkdir()
就足够了。
const char dir[] = "./sock";
const char fifo[] = "./sock/myfifo";
int fd;
if (mkdir(dir, 0755) == -1 && errno != EEXIST)
perror("Failed to create directory: ");
else if (mkfifo(fifo, 0600) == -1 && errno != EEXIST)
perror("Failed to create fifo: ");
else if ((fd = open(fifo, O_WRONLY)) < 0)
perror("Failed to open fifo for writing: ");
else
{
…use opened fifo…
close(fd);
}
我假设您包含正确的 headers,当然(<errno.h>
、<fcntl.h>
、<stdio.h>
、<stdlib.h>
、<sys/stat.h>
, <unistd.h>
, 我相信)。
请注意打开 FIFO 的 if
中赋值周围的括号。
我必须在 Ubuntu 的 C 程序中使用 mkfifo
。但是当我 运行 代码时出现错误:no such file or directory
.
我觉得问题是因为我没有设置panel_fifo
环境变量。但是我不知道我该怎么做。
这是我用来测试此方法的代码:
char *myfifo="./sock/myfifo";
if (mkfifo(myfifo,0777)<0)
perror("can't make it");
if (fd=open(myfifo,O_WRONLY)<0)
perror("can't open it");
我编译这个:
gcc gh.c -o gh
当我 运行 时,我收到此错误消息:
can't make it:no such file or directory
can't open it:no such file or directory
有关创建目录路径的通用 C(和 C++)解决方案,请参阅 How can I create a directory tree in C++/Linux。对于眼前的问题,这是矫枉过正,直接调用 mkdir()
就足够了。
const char dir[] = "./sock";
const char fifo[] = "./sock/myfifo";
int fd;
if (mkdir(dir, 0755) == -1 && errno != EEXIST)
perror("Failed to create directory: ");
else if (mkfifo(fifo, 0600) == -1 && errno != EEXIST)
perror("Failed to create fifo: ");
else if ((fd = open(fifo, O_WRONLY)) < 0)
perror("Failed to open fifo for writing: ");
else
{
…use opened fifo…
close(fd);
}
我假设您包含正确的 headers,当然(<errno.h>
、<fcntl.h>
、<stdio.h>
、<stdlib.h>
、<sys/stat.h>
, <unistd.h>
, 我相信)。
请注意打开 FIFO 的 if
中赋值周围的括号。