mknod() not creating named pipe

898 Views Asked by At

I'm trying to create a FIFO named pipe using the mknod() command:

int main() {
char* file="pipe.txt";
int state;
state = mknod(file, S_IFIFO & 0777, 0);
printf("%d",state);
return 0;
}

But the file is not created in my current directory. I tried listing it by ls -l . State returns -1.

I found similar questions here and on other sites and I've tried the solution that most suggested:

int main() {
char* file="pipe.txt";
int state;
unlink(file);
state = mknod(file, S_IFIFO & 0777, 0);
printf("%d",state);
return 0;
}

This made no difference though and the error remains. Am I doing something wrong here or is there some sort of system intervention which is causing this problem?

Help.. Thanks in advance

1

There are 1 best solutions below

4
On BEST ANSWER

You are using & to set the file type instead of |. From the docs:

The file type for path is OR'ed into the mode argument, and the application shall select one of the following symbolic constants...

Try this:

state = mknod(file, S_IFIFO | 0777, 0);

Because this works:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>


int main() {
    char* file="pipe.txt";
    int state;
    unlink(file);
    state = mknod(file, S_IFIFO | 0777, 0);
    printf("state %d\n", state);
    return 0;
}

Compile it:

gcc -o fifo fifo.c

Run it:

$ strace -e trace=mknod ./fifo
mknod("pipe.txt", S_IFIFO|0777)         = 0
state 0
+++ exited with 0 +++

See the result:

$ ls -l pipe.txt
prwxrwxr-x. 1 lars lars 0 Jul 16 12:54 pipe.txt