创建一个写进程和一个读进程,跟网上视频写的代码一样,但是到我自己电脑每次运行文件后创建的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;
}