C++ – Named pipes – Problem with write() and read()

cipcnamed-pipesprocess

I am doing programming in C++, under LINUX.
I have two independent processes. I should provide communication using named pipe.

Reader:
-creates FIFO using mkfifo – status = mkfifo(myFIFO, 0666)
-opens the pipe using open – fifo = open (myFIFO,O_RDONLY)
-reads from the pipe – num = read(fifo, temp, sizeof(temp))

Writer:
-opens pipe – fifo = open(myFIFO, O_WRONLY);
-writes to the pipe – num = write(fifo, string, strlen(string));

I have noticed that the file descriptor returned for read process
and write process are 0. Also, after command write, I can see on my terminal, the string which should be written to the pipe. I don't know why it is shown on terminal… Also, the number of bytes that are written is 0…

Would you please help me?
Thank you!!!

// read.cpp:

#define myFIFO "/temp/FIFO"

int main(){
    int num, fifo, status;
    char temp[32];

    if (status = mkfifo(myFIFO, 0666) < 0) { 
     printf("\n %s \n", strerror(errno));
     return 0;
     }

     if (fifo = open(myFIFO, O_RDONLY) < 0) { 
     printf("\n %s \n", strerror(errno));
     return 0;
     }

     if (num= read(fifo, temp, sizeof(temp)) < 0) { 
     printf("\n %s \n", strerror(errno));
     return 0;
     }

    printf("In FIFO is %s \n", temp);
}

And in another file:

// write.cpp:

#define myFIFO "/temp/FIFO"

int main() {
    int status, num, fifo;
    char string[]="Testing...";

     if (fifo = open(myFIFO, O_WRONLY) < 0) { 
     printf("\n %s \n", strerror(errno));
     return 0;
     }

     if (num= write(fifo, string, strlen(string)) < 0) { 
     printf("\n %s \n", strerror(errno));
     return 0;
     }
}

Best Answer

You basically have at least four errors in your code. When you create a FIFO, you have to use a file descriptor returned by "open" call. However, you are comparing it with 0 and assigning a result of a comparison to a variable that was meant to hold a file descriptor:

if (fifo = open(myFIFO, O_RDONLY) < 0) { 
    printf("\n %s \n", strerror(errno));
    return 0;
}

The correct code should look like this:

fifo = open(myFIFO, O_RDONLY);
if (fifo < 0) { 
    printf("\n %s \n", strerror(errno));
    return 0;
}

Or like this, if you insist of saving one line of code:

if ((fifo = open(myFIFO, O_RDONLY)) < 0) { 
    printf("\n %s \n", strerror(errno));
    return 0;
}

And exactly the same story with reading:

if (num= read(fifo, temp, sizeof(temp)) < 0) { 
    printf("\n %s \n", strerror(errno));
    return 0;
}

Correct code:

num = read(fifo, temp, sizeof(temp));
if (num < 0) { 
    printf("\n %s \n", strerror(errno));
    return 0;
}

In your code that writes to FIFO there exactly the same two errors.

Related Topic