tags:

views:

45

answers:

1

I'm trying to write a simple daemon in Linux, which will create a FIFO, then collect anything written to the FIFO and write that data to a file at a later time.

My expectations are that once my daemon has created the FIFO, I can do "echo text > /myfifo" repeatedly. When I'm done, I can do "echo quit > /myfifo" and my program will exit and write all data to disk.

I'm currently using poll() to know when there's more data on the FIFO. This works fine until after the first time I echo data to the FIFO. The data is echoed fine, but my poll continuously returns SIGHUP after that.

Do I need to reset (or close & reopen) the FIFO after each process writes to it?

Pseudo-code of my code looks like this:

ret = fifo(my_fifo, mode);
fd = open(my_fifo, O_RDONLY | O_NONBLOCK);

polling.fd = fd;
polling.events = POLLIN | POLLPRI;

do {
    ret = poll(&polling, 1, -1);
    amt = read(fd, buf, bufsize);
    // do stuff
} while (!done);
+2  A: 

You have to keep reopening the FIFO, I think. I have a program that monitors a FIFO, and the monitor loop is:

/* Implement monitor mode */
void sql_monitor(char *fifo)
{
    if (chk_fifo(fifo) != 0)
        cmd_error(E_NOTFIFO, fifo);

    /* Monitor -- device is assumed to be a FIFO */
    while (1)
    {
        ctxt_newcontext();
        if (ctxt_setinput(fifo) != 0)
            sql_exit(1);
        sql_file();
        ctxt_endcontext();
    }
}

The ctxt_newcontext() function stashes the current I/O state; the ctxt_setinput() function sets the input file to the named file - a FIFO in this case. The sql_file() function reads from the file (FIFO) until the end is reached - the file is closed. The ctxt_endcontext() undoes what ctxt_newcontext() does. The process repeats... This code has been around since about 1990.

So, YES, you will need to keep closing and reopening the FIFO after reading the end of the file (after each process such as echo finishes writing to the FIFO).

(You should also notice that there really isn't a need to poll the FIFO unless there's something else for the process to be doing when there is no data. The read() call will wait until there is data before returning.)

Jonathan Leffler
Yes, FIFO has to be reopened. Many forget that in sync mode, opening FIFO would block until other side of communication opens it too. That is to make it usable for e.g. shell redirections. So in a way it behaves like a connection.
Dummy00001