Search code examples
cpipemknod

C: creating named pipe using mknod() not working


Language: C OS: Ubuntu

I'm simply trying to create a FIFO named pipe using the command:

state = mknod("pipe.txt", S_IFIFO | 0666, 0);

the problem is i always get the state's value to be -1 (meaning it has failed) instead of 0.

perror returns 'pipe.txt: File exists'

i have no idea how should i debug such issue or what could be the reason, hope anyone code guide me what's wrong.

(note: the file pipe.txt exist on same path as source file.)


Solution

  • Read: int mknod(const char *path, mode_t mode, rdev_t dev_identifier);
    General Description:
    Creates a new character special file or FIFO special file (named pipe), with the path name specified in the path argument.

    If file already exists then it will fails with error: File exists

    To avoid this error, remove(unlink()) the file, As I am doing in my below code(read comment):

    int main() {
      char* file="pipe.txt";
      unlink(file);  // Add before mknod()
      int state = mknod(file, S_IFIFO | 0666, 0);
      if(state < 0){
        perror("mknod() error");
      }
      return 0;
    }