本次进程间通信使用了消息队列,编写了两个程序,一个用于发送消息,一个用于读取消息.
发送消息msgWrite.c如下:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <signal.h>
void *pAddr;
int msgId;
struct MSG{//msgsnd要填入的消息参数格式
long mtype;
char content[36];
};
struct Student{
int id;
char name[32];
};
void Handle(int s){
if(s == 2)
{
msgctl(msgId,IPC_RMID,0);
exit(0);
}
}
int main(){
signal(2,Handle);//ctrl+c键退出程序时删除消息队列
key_t key = ftok(".",4);
msgId = msgget(key,IPC_CREAT | IPC_EXCL | 0666);
if(msgId == -1){
printf("shmat error!\n");
exit(0);
}
int stuid = 0;
struct Student stu;
struct MSG msg;
while(1){
stuid++;
stu.id = stuid;
printf("input name:");
scanf("%s",stu.name);
msg.mtype = 2;
memcpy(msg.content,&stu,sizeof(stu));
msgsnd(msgId,&msg,sizeof(msg),0);
}
return 0;
}
读消息msgRead.c如下:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <signal.h>
void *pAddr;
int msgId;
struct MSG{
long mtype;
char content[36];
};
struct Student{
int id;
char name[32];
};
int main(){
key_t key = ftok(".",4);
msgId = msgget(key,0);
if(msgId == -1){
printf("shmat error!\n");
exit(0);
}
struct MSG msg;
while(1){
if(msgrcv(msgId,&msg,sizeof(msg),2,0) == -1)//若发送消息程序已退出,则本程序也退出
{
exit(0);
}
else{
struct Student *stu = (struct Student *)msg.content;
printf("%d : %s\n",stu->id,stu->name);
}
}
return 0;
}
运行结果如下: