views:

60

answers:

1

Hi,

I use the following program to write to a 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;
}

If I start this program, start another shell and type there

cat < fifo1

I can see that the program writes something to the pipe and I can see the output in the reading shell. If I stop the cat command with CTRL^C also the FIFO Writer termintes, with no error message. What is the reason for this? Why is no error thrown?

The weird thing is, if I start the above code with Eclipse CDT and the reading shell is closed with CTRL^C the program continues printing "Error: 3".

Looking forward to your ideas, heinrich

+3  A: 

If you write to a pipe when the other end of the pipe has been closed a SIGPIPE will be delivered to your process. Without an installed signal handler, this will kill your process immediately. Normally this is output, I don't know why do do not see this.

If you rather like to check the error codes of write than get a SIGPIPE as your code suggests, you have to ignore SIGPIPE:

#include <signal.h>

signal( SIGPIPE, SIG_IGN );
Peter G.
As of bash-3.1, bash does not report SIGPIPE errors by default.
Alexandre Jasmin
@Alexandre, thanks then everything might be explained now
Peter G.
Thanks for the answer, that was the problem!
Heinrich