2

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

aashima
  • 1,203
  • 12
  • 31

1 Answers1

1

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
larsks
  • 277,717
  • 41
  • 399
  • 399
  • It's not clear why you've changed it to something that is obviously incorrect based on the documentation. ANDing the value with the mode is just going to result in `0`, which will create a normal file with no permissions. – larsks Jul 16 '15 at 16:55
  • I've updated this answer with the behavior I see on my system. – larsks Jul 16 '15 at 16:55
  • Hey! that worked. Thanks so much.. But I wonder why my program won't work :(.. Are all the above header files needed for the program?? – aashima Jul 16 '15 at 17:04
  • I just used the `#include`'s the man page for `mknod` said to use. That seems like the best course of action. If I remove everything other than `#include ` it still seems to work, although there are of course a number of warnings. – larsks Jul 16 '15 at 17:11
  • I see.. ok. Thanks for your help :) – aashima Jul 16 '15 at 17:16