操作系统实验代码
snd.c
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <stdio.h>
#define key 80
struct msg {
long mtype;
int snd_id;
char txt[128];
};
int len=sizeof(struct msg) - sizeof(long);
main()
{
int qid;
struct msg m;
qid=msgget(key,0777|IPC_CREAT);
m.mtype=1;
m.snd_id=getpid();
strcpy(m.txt,"aaaaa");
printf("qid=%d\n",qid);
msgsnd(qid,&m,len,0);
msgrcv(qid,&m,len,getpid(),0);
printf("pid=%d,%s\n",m.snd_id,m.txt);
getchar();
}
rcv.c
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <stdio.h>
#define key 80
struct msg {
long mtype;
int snd_id;
char txt[128];
};
int len=sizeof(struct msg) - sizeof(long);
main()
{
int qid;
int pid=getpid();
struct msg m;
qid=msgget(key,0777);
printf("qid=%d",qid);
msgrcv(qid,&m,len,1,0);
printf("pid=%d,%s\n",m.snd_id,m.txt);
m.mtype=m.snd_id;
m.snd_id=pid;
strcpy(m.txt,"bbbbb");
msgsnd(qid,&m,len,0);
getchar();
}