在单个过程中使用命名管道 [英] Using named pipes in a single process

查看:98
本文介绍了在单个过程中使用命名管道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用命名管道在进程内进行通信. 这是代码

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;
}

我要的是让main阻塞,直到将某些内容写入管道为止. 问题在于,打开管道后,信号处理程序sigint()也将阻塞.考虑到管道已经打开以便在main()中更早读取,是否应该发生这种情况?

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() ?

推荐答案

您正在阻塞open(),打开一个fifo读取块,直到有人打开它进行写入.

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

然后打开一个fifo来编写块,直到有人打开它以供阅读为止.

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

信号处理程序与main()在同一线程中运行,因此会出现死锁.两者都将无法打开fifo.

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.

您可以通过在strace下运行程序来检查发生了什么.

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

这篇关于在单个过程中使用命名管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆