linux fifo有名管道 ,可以用来给进程通信,但是write写的时候,发生了不正确的解析,自己整了2天,没搞清楚原因,希望大神来解答一下
写端:
struct msg
{
int id;
char message[255];
};
int main(void)
{
struct msg mym;
mym.id=123;
sprintf(mym.message,"hello china");
int ff=fifo("usr/myfifo",0777);
if(ff<0)
{
perror("fifo fail");
exit(1);
}
int fd=open("usr/myfifo",O_WRONLY);
if(fd<0)
{
perror("open fail");
exit(2);
}
write(fd,&mym,sizeof(mym));
close(fd);
return 0;
}
读端:
struct msg
{
int id;
char message[255];
};
int main(void)
{
struct msg mym;
int fd=open("usr/myfifo",O_RDONLY);
if(fd<0)
{
perror("open fail");
exit(2);
}
read(fd,&mym,sizeof(mym));
printf("id=%d,msg:%s",mym.id,mym.message);
unlink("usr/myfifo");
close(fd);
return 0;
}
自己测试 读端msg结构体的对象,能正确读出int成员的值,无法正确读出char*的值,自己不清楚原因。 有种感觉是申请对象内部有脏内存存在,导致解析失败。
自己的问题自己找到答案了,struct 内存对齐导致,传递不准确