0

When my program starts, it just creates a fifo and opens it, after that I just want to output some information to the screen, however, nothing gets printed out. Here's a snippet of my code:

void listen(const server_config_t* server_conf)
{
    // Create FIFO
    if (mkfifo(SERVER_FIFO_PATH, 0660) == -1) {
        fprintf(stdout, "server FIFO not created as it already exists. continuing...\n");
    }

    // Open FIFO (for reading)
    int fd;
    if ((fd = open(SERVER_FIFO_PATH, O_RDONLY)) == -1) {
        // fprintf(stderr, "error: could not open server FIFO\n");
        perror("FIFO");
        exit(1);
    }

    // Open dummy FIFO (for writing, prevent busy waiting)
    // TODO: find way to wait without another file descriptor?
    int fd_dummy;
    if ((fd_dummy = open(SERVER_FIFO_PATH, O_WRONLY)) == -1) {
        perror("DUMMY FIFO");
        exit(1);
    }

    // TODO: this should print immediately after starting,
    //       but doesn't for some reason
    fprintf(stdout, "server listening... %d %s\n", server_conf->num_threads,
        server_conf->password);
    fflush(stdout);

.
.
.

}

Here's my output:

Here's the output

I've tried commenting out the fifo creation and opening, and when I do that the message gets printed correctly to the screen.

136
  • 1,083
  • 1
  • 7
  • 14

2 Answers2

5

Opening a FIFO normally blocks until the other end is opened as well, see http://man7.org/linux/man-pages/man7/fifo.7.html. So your program probably waits in open(SERVER_FIFO_PATH, O_RDONLY) and does not reach any other fprintf or perror.

Your attempt to open the FIFO for reading first and then for writing does not work because the first open does not return.

You should be able to see this when you step through your program using a debugger.

BTW: When mkfifo returns -1 you should check if errno is EEXIST. There could be other errors that would also result in return value -1, see https://linux.die.net/man/3/mkfifo

Bodo
  • 9,287
  • 1
  • 13
  • 29
2

As you can see from your output, there is blocking. That is, your current process cannot go on until the other end of the FIFO is opened for write. You should glance at the man page.

As to your error, there are two cases maybe the directory into which you want to place the FIFO doesn't permit to do that. Second case may be due to a system error. To overcome the issue, you need to change your fprintf as following.

#include <string.h>
#include <stdlib.h>
..
..
fprintf(stderr, "server FIFO not created as it already exists. Error: %s\n", strerror(errno));
exit(EXIT_FAILURE);