Named pipes - problem with write () and read ()

I do C ++ programming under LINUX. I have two independent processes. I have to provide communication using a named pipe.

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

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

I noticed that the file descriptor was returned for the reading process and the writing process is 0. In addition, after the write command, I can see a line on my terminal that should be written to the channel. I do not know why this is shown on the terminal ... Also, the number of bytes written is 0 ...

Could you help me? Thank!

// 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;
     }
}
+3
source share
2 answers

There are at least four errors in the code. When you create a FIFO, you must use the file descriptor returned by the "open" call. However, you compare it with 0 and assign the result of the comparison with a variable designed to store the 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, for example, if you insist on keeping one line of code:

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

And the exact same story with reading:

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

The correct code is:

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

There are exactly the same two errors in your code that writes to FIFO.

+8
source

: fifo = open(myFIFO, O_WRONLY) < 0 fifo = (open(myFIFO, O_WRONLY) < 0). , open() >= 0.

+1

Source: https://habr.com/ru/post/1758724/


All Articles