Using named pipes in a single process

谁说胖子不能爱 提交于 2019-12-12 15:52:21

问题


I am trying to use a named pipe for communication within a process. Here is the code

#include <stdio.h>
#include <fcntl.h>
#include <signal.h>

void sigint(int num)
{
    int fd = open("np", O_WRONLY);
    write(fd, "y", 1);
    close(fd);
}

main()
{
    char ch[1];
    int fd;

    mkfifo("np", 0666);

    signal(SIGINT, sigint);

    fd = open("np", O_RDONLY);

    read(fd, ch, 1);

    close(fd);

    printf("%c\n", ch[0]);
    return;
}

What I want is for main to block till something is written to the pipe. The problem is that the signal handler sigint() also blocks after opening the pipe. Is this supposed to happen given that the pipe is already opened for reading earlier in main() ?


回答1:


You're blocking in open() , opening a fifo for reading blocks until someone opens it for writing.

And opening a fifo for writing blocks until someone opens it for reading.

the signal handler runs in the same thread as your main(), so you'll get a deadlock. Neither will be able to open the fifo.

You can check what's going on by running your program under strace.




回答2:


From the man page:

Opening a FIFO for reading normally blocks until some other process opens the same FIFO for writing, and vice versa.

and:

A process can open a FIFO in non-blocking mode. In this case, opening for read only will succeed even if no-one has opened on the write side yet; opening for write only will fail with ENXIO (no such device or address) unless the other end has already been opened.

Under Linux, opening a FIFO for read and write will succeed both in blocking and non-blocking mode. POSIX leaves this behaviour undefined. This can be used to open a FIFO for writing while there are no readers available. A process that uses both ends of the connection in order to communicate with itself should be very careful to avoid deadlocks.



来源:https://stackoverflow.com/questions/2251710/using-named-pipes-in-a-single-process

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!