Search code examples
clinuxmkfifo

Give permissions from super user process in mkfifo


I need to create a pipe using mkfifo() from a super user process, that pipe must be writable from a process not super user.

Reader:

int main () {
  char *myfifo = "/tmp/myfifo";
  int buf;
  mkfifo(myfifo, 0777); //problem here

  FILE *fp;
  fp = fopen(myfifo,"r");
  if ( fp == NULL) {
    unlink(myfifo);
    return -1;
  }
  printf("received: %d\n",buf);

  fclose(fp);
  unlink(myfifo);
  return 0;
}

Writer:

int main() {
  FILE *fp;
  char *myfifo = "/tmp/myfifo";

  fp = fopen(myfifo,"w");
  if ( fp == NULL)
    return -1;

  fprintf(fp, "%d ", 2);
  fclose(fp);
  return 0;
}

I call ./writer and sudo ./reader.

When my writer try to write in the pipe that return a segmentation fault. And if I look in /tmp/myfifo I found that permissions prwxr-xr-x, but I want prw-rw-rw-.


Solution

  • Your writer is segfaulting because you are opening it for writing, but do not have permissions to write to it. Hence fp will be NULL, and your fprintf fails.

    The reason for your FIFO having incorrect permissions is probably because your umask is 022, which means those bits are being cleared from the mask you send to mkfifo. This will result in the permissions you see. To fix this, either change your umask using the umask call, or explicitly set permissions with chmod.

    But do you really want your FIFO to be executable?