Reading from FIFO after unlink ()

I created a FIFO, wrote to him and disconnected it. To my surprise, I was able to read the data from fifo after the conversation, why?

#include <fcntl.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

#define MAX_BUF 256
int main()
{
    int fd;
    char * myfifo = "/tmp/myfifo";

    /* create the FIFO (named pipe) */
    mkfifo(myfifo, 0666);

    int pid = fork();
    if (pid != 0)
    {
        /* write "Hi" to the FIFO */
        fd = open(myfifo, O_WRONLY);
        write(fd, "Hi", sizeof("Hi"));
        close(fd);

        /* remove the FIFO */
        unlink(myfifo);
    }
    else 
    {
        wait(NULL);
        char buf[MAX_BUF];

        /* open, read, and display the message from the FIFO */
        fd = open(myfifo, O_RDONLY);
        read(fd, buf, MAX_BUF);
        printf("Received: %s\n", buf);
        close(fd);

        return 0;
    }


    return 0;
}
+4
source share
1 answer

If you don't pass the flag O_NONBLOCKon open(2), open the FIFO blocks until the other end opens. From man 7 fifo:

FIFO must be open at both ends (read and write) before data can be transferred. Usually, opening FIFO blocks to the other end also opens.

FIFO . , ENXIO ( ), .

, / FIFO. , unlink(2), FIFO. , FIFO , unlink(2).

unlink(2): unlink(2) ; (FIFO ), . , , . FWIW, , , , .

() :

  • wait(2) . ( ), - .
  • mkfifo(3), fork(2), open(2), read(2), write(2), close(2) unlink(2) -1. , . perror(3) .
  • , , : , , ( pipe(2) forking, ).
+1

All Articles