c - fifo文件关闭时读取器进程终止



我写了一对简单的读写程序。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 ("byebyen");
    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 openingn");
    int fd = open ("myfifo", O_RDONLY);
    if (fd == -1) {
        perror ("opening fifo");
        exit (1);
    }
    printf ("bef readingn");
    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信号,然后自己处理写入错误。

最新更新