Search code examples
cunixiopipefile-descriptor

Bad file number in simple main function with pipes


I am still a baby in C world and I was doing some "system" programming in order to do some exercises when I stumbled upon some error which is obvious, but I can't find the problem within my application

This is the code

const int __WRITE_ERROR = 44;
const int __READ_ERROR = 43;

const int READ = 0;
const int WRITE = 1;
const int MAX = 1024;

int main(int argc, char *argv[]) {
    int fd[2], n;
    char buff[MAX];

    if(pipe(&fd[2]) < 0)
        exit(__PIPE_ERROR);
    printf("Hello, from pipe: write: %d and read: %d\n", fd[WRITE], fd[READ]);

    if(write(fd[WRITE], "Hello World\n", 12) != 12) {
        printf("Explanation: %i", errno); // <- constantly comes here with errno 9 for some reason.
        exit(__WRITE_ERROR);
    }

    if((n = read(fd[READ], buff, MAX)) != 0)
        exit(__READ_ERROR);

    write(1, buff, n);
    exit(0);
}

Could you help me out, cause I ran out of options, thanks.


Solution

  • There is a problem with:

    if (pipe(&fd[2]) < 0)
    

    It should be instead:

    if (pipe(fd) < 0)
    

    The former is passing to pipe() the address of one element past of the bounds of the array fd (i.e.: the &fd[2]).


    Also, read() and write() return the number of bytes read or written, respectively. However, if an error occurs -1 is returned for both functions.