【问题标题】:Reader-process termination on FIFO-file closingFIFO 文件关闭时的读取器进程终止
【发布时间】:2016-08-23 18:44:55
【问题描述】:

我编写了一对简单的读写器程序。 Writer 创建/打开一个 FIFO 文件,并不断向其中写入一个字符串。读者只是在阅读它并写入标准输出。读者只这样做了 10 次,然后退出。令人惊讶的是(对我来说)作者也几乎立即退出了。它不仅超出了写作循环,而且似乎跳出了它,我可以通过在屏幕上看不到最后的“再见”来判断它。我可以接受这种行为,但我仍然不明白为什么。 有人可以与我分享他们的知识吗?

/* writer code */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>

int main()
{
    char msg [] = "Leo_Tolstoy";

    size_t len = strlen("Leo_Tolstoy");

    if (mkfifo ("myfifo", 0600) != 0) {
        perror ("creating fifo");
    }
    int fd;
    if ( (fd = open ("myfifo", O_WRONLY)) == -1) {
        perror ("opening fifo");
        exit (1);
    }
    while (1)
    {
        int r = write (fd, msg, len);
        if (r == -1)
            perror ("writing");
        sleep(1);
    }
    printf ("byebye\n");
    close (fd);
    return 0;
}
/* reader code */
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/shm.h>

int main()
{
    char buf[50];

    printf ("bef opening\n");
    int fd = open ("myfifo", O_RDONLY);
    if (fd == -1) {
        perror ("opening fifo");
        exit (1);
    }

    printf ("bef reading\n");
    int cnt=0;
    while (cnt < 10)
    {
        int r = read (fd, buf, 50);
        if (r == 0)
            break;
        if (r == -1)
            perror ("reading");
        write (1, buf, r);
        cnt++;
    }
//  close (fd);
    return 0;
}

【问题讨论】:

  • 所以,C 或 C++。我会说 C,但那是你的决定。请选择 一种 语言,而不是 2 种(您的问题似乎不适用于不同的语言)。
  • 没有语言 C/C++,只有两种不同的语言 C 和 C++。选择其中一个
  • 调试器说什么?
  • 我选择了 C)。我没有使用调试器,很遗憾,但我不知道如何使用 gdb,而且我现在没有安装 IDE(它只是一个带有 Ubuntu 14.04 的 VM)
  • if (mkfifo ("myfifo", 0600) != 0) 使用八进制值,如果相关,则为十进制 384。

标签: c glibc mkfifo


【解决方案1】:

当退出时(经过 10 次迭代),由于读取端被关闭,写入者会收到 SIGPIPE。因此,执行信号SIGPIPE 的默认操作以终止程序。这就是为什么你看不到最终的 printf() 没有被执行。

相反,您可以通过调用sigaction() 来忽略(SIG_IGN)写入器中的信号SIGPIPE,然后自己处理写入错误。

【讨论】:

  • 好吧,现在我已经为 SIGPIPE 指定了一个信号处理程序,一切似乎都正常了。谢谢。
猜你喜欢
  • 2020-08-16
  • 2011-08-22
  • 2020-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多