1

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

I think the problem because I have not set the panel_fifo environment variables. But I don't know 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
Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
ghadeer darwesh
  • 185
  • 1
  • 3
  • 12
  • 1
    Have you created a directory `sock` in the current directory? If not, that's the trouble. You are also missing parentheses around the assignment in the second `if` statement. – Jonathan Leffler May 27 '15 at 03:10
  • It's likely because the `sock` directory doesn't exist. Issue a `mkdir -p sock/myfifo` in the CWD and it should work after making the fixes suggested by @JonathanLeffler – erip May 27 '15 at 03:21

1 Answers1

3

See How can I create a directory tree in C++/Linux for a general C (and C++) solution to creating a directory path. For the immediate problem, that is overkill and a direct call to mkdir() suffices.

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

I'm assuming you have the correct headers included, of course (<errno.h>, <fcntl.h>, <stdio.h>, <stdlib.h>, <sys/stat.h>, <unistd.h>, I believe).

Note the parentheses around the assignment in the if that opens the FIFO.

Community
  • 1
  • 1
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • Note that if `./sock/myfifo` is a directory, the `mkfifo()` will fail, but it will be the `open()` that reports an error (because the error from `mkfifo()` is EEXIST). So, this isn't perfect in its error reporting, but given a sane starting position (`sock` either doesn't exist or is a directory — rather than, say, a file or FIFO; and `myfifo` either doesn't exist or is a FIFO), and assuming that something opens the FIFO for reading (e.g. I tested with `O_RDWR` instead of `O_WRONLY`), then it works OK. – Jonathan Leffler May 27 '15 at 04:21