0

我在 C 中使用命名管道将结构从一个程序传输到另一个程序。当我按原样执行程序时,我意识到在阅读方面我并没有阅读我应该阅读的所有内容。似乎读取或写入过程都会跳过一些值(但数据永远不会损坏,它是否存在或不存在)。在 gdb 中调试时,我可以看到一段时间后(每次持续时间的长度都是随机的),程序以 SIGPIPE: Broken pipe 结束。

然后,我意识到在编写程序中引入 1 秒的延迟可以解决这个信息丢失的问题。我阅读了我应该在接收方阅读的所有内容。

下面是编写程序的代码:

// 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; 
} 
4

0 回答 0