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

このプログラムを起動したら、別のシェルを起動してそこに入力します

cat < fifo1

プログラムがパイプに何かを書き込んでいることがわかり、読み取りシェルで出力を確認できます。CTRL^C を使用して cat コマンドを停止すると、FIFO Writer も終了し、エラー メッセージは表示されません。これの理由は何ですか?エラーがスローされないのはなぜですか?

奇妙なことに、Eclipse CDT で上記のコードを開始し、読み取りシェルを CTRL^C で閉じると、プログラムは "Error: 3" を出力し続けます。

あなたのアイデアを楽しみにしています、ハインリッヒ

4

1 に答える 1

3

パイプのもう一方の端が閉じられているときにパイプに書き込むと、SIGPIPE がプロセスに配信されます。シグナルハンドラーがインストールされていない場合、これによりプロセスがすぐに強制終了されます。通常はこれが出力されますが、なぜこれが表示されないのかわかりません。

コードが示すように SIGPIPE を取得するよりも書き込みのエラー コードを確認したい場合は、SIGPIPE を無視する必要があります。

#include <signal.h>

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