创建一个写进程和一个读进程,跟网上视频写的代码一样,但是到我自己电脑每次运行文件后创建的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;
}
只要两个进程打开文件的绝对路径一样,就可以了。比如你的两个文件的目录不是同一个,那么你的./a.c就是不一样的。其次,你在每次创建之后最后msgctl删除了消息队列,下一次自然随机分配。并且好像每次比上一次大2的16次方。也就是比上一次大32768。也就是说只要你打开的绝对路径是一样的,那么大家的key值就是一样的。获取到的也是一样,你不删除每次打开的就是以前那个消息队列。key值是三部分组成。你传入的字符'a',inode,以及dev三类组成,分别取不同的某几位数组成key的值。