0

我使用以下程序写入 fifo:

#include <iostream>
#include <fstream>

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

using namespace std;

int main() {

    unlink("fifo1");

    if (mkfifo("fifo1", 0666) != 0) {
        cout << "Error while creating fifo" << endl;
        return 1;
    }
    else {
        cout << "Fifo created" << endl;
    }

    int fd = open("fifo1", O_WRONLY);
    if(fd == -1) {
        cout << "Could not open file" << endl;
        return 1;
    }
    else {
        cout << "Fifo opened" << endl;
    }


    int i=0;
    char* buffer = new char[20];
    while(true) {
        sprintf(buffer, "look: %i\n", i++);

        int r = write(fd, buffer, strlen(buffer));
        if(r == -1) {
            cout << "Fifo Error:" << fd << endl;
        }
        else {
            cout << "Wrote: " << i << "(" << r << "B)"<< endl;
        }
        sleep(1);
    }

    return 0;
}

如果我启动这个程序,启动另一个 shell 并在那里输入

cat < fifo1

我可以看到程序向管道写入了一些内容,并且我可以在读取 shell 中看到输出。如果我用 CTRL^C 停止 cat 命令,FIFO Writer 也会终止,没有错误消息。这是什么原因?为什么没有抛出错误?

奇怪的是,如果我用 Eclipse CDT 启动上面的代码并用 CTRL^C 关闭读取 shell,程序会继续打印“错误:3”。

期待你的想法,海因里希

4

1 回答 1

3

如果您在管道的另一端已关闭时写入管道,则会将 SIGPIPE 传送到您的进程。如果没有安装信号处理程序,这将立即终止您的进程。通常这是输出,我不知道为什么看不到这个。

如果您更喜欢检查写入的错误代码而不是按照代码建议的方式获取 SIGPIPE,则必须忽略 SIGPIPE:

#include <signal.h>

signal( SIGPIPE, SIG_IGN );
于 2010-10-21T20:05:04.213 回答