Vickers Q 2021-01-31 11:47 采纳率: 0%
浏览 33

linux 中进程间通信 创建的消息队列ID号不一样的问题怎么回事?

创建一个写进程和一个读进程,跟网上视频写的代码一样,但是到我自己电脑每次运行文件后创建的msgid号不一样,导致两个进程通信不了

写进程:

#include "sys/types.h"
#include "sys/msg.h"
#include "signal.h"
#include "unistd.h"
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
struct msgbuf
{
 long type;
 char mtext[124];
 char ID[4];
};

int main()
  {
  int msgid;
  int key;
  struct msgbuf sendbuf,recvbuf;
  int readret;
  key=ftok("./a.c",'a');
  if(key<0)
   {
   printf("creat key failure\n");
   return -2;
   }
  msgid=msgget(key,IPC_CREAT|0777);
   if(msgid < 0)
   {
   printf("creat msg memory failure\n");
   return -1;
   }
  printf("creat msg memory sucess migid=%d\n",msgid);
  system("ipcs -q");

  while(1)
  {
   memset(sendbuf.mtext,0,124);
  //init sendbuf
  sendbuf.type=100;
  printf("please input message:\n");
  fgets(sendbuf.mtext,124,stdin);
  //start write message
  msgsnd(msgid,(void *)&sendbuf,strlen(sendbuf.mtext),0);
  }

  //delate
  msgctl(msgid,IPC_RMID,NULL);
  system("ipcs -q");
  return 0;
  }
 

读进程:

#include "sys/types.h"
#include "sys/msg.h"
#include "signal.h"
#include "unistd.h"
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
struct msgbuf
{
 long type;
 char mtext[124];
 char ID[4];
};

int main()
  {
  int msgid;
  int key;
  struct msgbuf sendbuf,recvbuf;
  int readret;
  key=ftok("./a.c",'a');
  if(key < 0)
   {
   printf("creat key failure\n");
   return -2;
   }
  msgid=msgget(key,IPC_CREAT|0777);
   if(msgid < 0)
   {
   printf("creat msg memory failure\n");
   return -1;
   }
  printf("creat msg memory sucess migid=%d\n",msgid);
  system("ipcs -q");
  
  while(1)
  {
 //start read message
  memset(recvbuf.mtext,0,124);
  readret=msgrcv(msgid,(void *)&recvbuf,124,100,0);
  printf("recv data message:%s",recvbuf.mtext);
  printf("readret=%d\n",readret);
  }
  //delate
  msgctl(msgid,IPC_RMID,NULL);
  system("ipcs -q");
  return 0;
  }
 

 

  • 写回答

1条回答 默认 最新

  • 嵌入式小企鹅 2023-09-21 13:52
    关注

    只要两个进程打开文件的绝对路径一样,就可以了。比如你的两个文件的目录不是同一个,那么你的./a.c就是不一样的。其次,你在每次创建之后最后msgctl删除了消息队列,下一次自然随机分配。并且好像每次比上一次大2的16次方。也就是比上一次大32768。也就是说只要你打开的绝对路径是一样的,那么大家的key值就是一样的。获取到的也是一样,你不删除每次打开的就是以前那个消息队列。key值是三部分组成。你传入的字符'a',inode,以及dev三类组成,分别取不同的某几位数组成key的值。

    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器