Reader-FIFO 文件关闭时进程终止

Reader-process termination on FIFO-file closing

我编写了一对简单的 reader-writer 程序。 Writer creates/opens 一个 FIFO 文件,并不断地向其中写入一个字符串。 reader 只是读取它并写入标准输出。 reader 仅执行 10 次,然后退出。令人惊讶的是(对我来说)作者几乎也立即退出了。它不只是跳出了写循环,它似乎跳出了它,我可以通过在屏幕上没有看到最后的 "byebye" 来判断。我可以接受这样的行为,但我仍然不明白为什么。 有人可以和我分享他们的知识吗?

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

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

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