0

I'm using named pipes in C to transfer struct from one program to the other. When I just execute the programs as they are, I realized that on the reading side I'm not reading everything that I'm supposed to read. It seems that either reading or writing process skips some values (yet the data is never corrupted, it's either there or not). While debugging in gdb, I can see that after some time (the length of duration is random each time), the program ends with SIGPIPE: Broken pipe.

Then, I realized introducing a delay of 1 second to the writing program fixes this issue with loss of information. I read everything I'm supposed to read on the receiving side.

Below is the code for the writing program:

// C program to implement one side of FIFO 
// This side writes first, then reads 
#include <stdio.h> 
#include <string.h> 
#include <fcntl.h> 
#include <sys/stat.h> 
#include <sys/types.h> 
#include <unistd.h> 

typedef struct
{
  float V;
  float A;
  float AR;
  float ALR;
  float Y;
  float YR;
  uint S;
  uint v;
} EgoV;

int main() 
{ 
    int fd; 

    // FIFO file path 
    char * myfifo = "/tmp/myfifo"; 

    // Creating the named file(FIFO) 
    // mkfifo(<pathname>, <permission>) 
    mkfifo(myfifo, 0666); 

    char arr1[80], arr2[80]; 

    EgoV my_ego;
    my_ego.V = 1.2;
    my_ego.A = 2.2;
    my_ego.AR = 3.2;
    my_ego.ALR = 4.2;
    my_ego.Y = 5.2;
    my_ego.YR = 6.2;
    my_ego.S = 7;
    my_ego.v = 1;

    while(1)  
    { 
        // Open FIFO for write only 
        fd = open(myfifo, O_WRONLY); 

        // fgets(arr2, 80, stdin);
        sleep(1);

        write(fd, &my_ego, sizeof(EgoV));
        close(fd);

        printf("Writer: %f\n", my_ego.VLgt); 

        my_ego.V = my_ego.V + 1;
        if(my_ego.V>1000)
            my_ego.V = 0.0;

    } 
    return 0; 
} 
gisil
  • 71
  • 1
  • 4
  • 1
    Welcome to stackoverflow. Please make yourself familiar with asking questions [here](https://stackoverflow.com/help/how-to-ask). Actually it's not clear what your question is. – rbf Dec 17 '19 at 07:56
  • Every time you read() or write() something, you have to check the results to see if the operation succeded, succeded only partly, or failed. You can **not** assume that the system can always carry out your requests correctly; sometimes it can not. Putting that sleep() in, you give some breath to the system, but it is not enough. – linuxfan says Reinstate Monica Dec 17 '19 at 08:41
  • thanks @linuxfansaysReinstateMonica, thats what I assumed as well. I have encountered very similar phenomenon with the TCP communication as well. Do you know if there is a better way of handling this, because eve when I check the result of the read and write operations, if the result is partly succeed or fail, I cannot retrieve the lost data. Whereas, I need to make sure each and every piece of data at every time is transferred. – gisil Dec 17 '19 at 12:00

0 Answers0