简体   繁体   English

如何用C制作fifo?

[英]How to make a fifo in C?

I have to use mkfifo in my C program in Ubuntu. 我必须在Ubuntu的C程序中使用mkfifo But I have an error when I compile: no such file or directory . 但是我编译时出错: no such file or directory

I think the problem because I have not set the panel_fifo environment variables. 我认为是问题所在,因为我尚未设置panel_fifo环境变量。 But I don't khow how could I do this. 但是我不知道该怎么做。

Here is my code I use to test this method: 这是我用来测试此方法的代码:

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");

I compile this with: 我用以下代码编译:

gcc gh.c -o gh

When I run, I get this error message: 运行时,出现以下错误消息:

can't make it:no such file or directory
can't open it:no such file or directory

It's because the directory sock doesn't exist. 这是因为目录袜子不存在。

In a terminal: 在终端中:

christian@fujiu1404:~/tmp/t2$ ls
t2.c
christian@fujiu1404:~/tmp/t2$ cat t2.c 
#include <fcntl.h>

main() {

int fd;
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");

}
christian@fujiu1404:~/tmp/t2$ cc t2.c
christian@fujiu1404:~/tmp/t2$ ./a.out 
can't make it: No such file or directory
can't open it: No such file or directory
christian@fujiu1404:~/tmp/t2$ mkdir sock
christian@fujiu1404:~/tmp/t2$ ./a.out 

Note the program hasn't completed, but your fifo does exist. 请注意,该程序尚未完成,但是您的fifo确实存在。

Now in a second terminal, put a string into the fifo 现在在第二个终端中,将字符串放入fifo

christian@fujiu1404:~/tmp/t2$ ls -l sock/
total 0
prwxrwxr-x 1 christian christian 0 May 27 06:45 myfifo
christian@fujiu1404:~/tmp/t2$ echo abc >sock/myfifo 

Note echo also is suspended 注意回声也被暂停

Now in a third terminal, read from the fifo 现在在第三个终端中,从fifo中读取

christian@fujiu1404:~/tmp/t2$ cat sock/myfifo 
abc
christian@fujiu1404:~/tmp/t2$ 

Note now all programs complete and exit (in all terminals) 现在注意所有程序都已完成并退出(在所有终端中)

You try 你试试

myfifo("./sock/myfifo", ...)

You get 你得到

no such file or directory 没有相应的文件和目录

which is ENOENT . 这是ENOENT

You then want to look up the relevant documentation and find the following in man 3 mkfifo : 然后,您想查找相关文档并在man 3 mkfifo找到以下内容:

ERRORS 错误

[...] [...]

ENOENT A directory component in pathname does not exist or is a dangling symbolic link. ENOENT路径名中的目录组件不存在或为悬挂的符号链接。

From all this one could conculde ./sock does not exist. 从所有这一切可能会混淆./sock不存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM