简体   繁体   中英

How to make a fifo in C?

I have to use mkfifo in my C program in Ubuntu. But I have an error when I compile: no such file or directory .

I think the problem because I have not set the panel_fifo environment variables. 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.

Now in a second terminal, put a string into the 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

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 .

You then want to look up the relevant documentation and find the following in man 3 mkfifo :

ERRORS

[...]

ENOENT A directory component in pathname does not exist or is a dangling symbolic link.

From all this one could conculde ./sock does not exist.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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