Question

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.)

Was it helpful?

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

OTHER TIPS

You should examine errno to see what the error is but it's probably EEXIST since I believe that's what happens if the file already exists.

From the Linux documentation for mknod:

If pathname already exists, or is a symbolic link, this call fails with an EEXIST error.

However, if the file already exists and is the pipe you created in an earlier run, you can safely reopen it. All mknod (and its often preferred cousin, mkfifo) does is actually create the FIFO, you still have to open it at both ends to get the data transfer happening.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top