實現功能:
編寫程序sender,它創建一個消息隊列;然後,循環等待用戶通過終端輸入一串字符,將這串字符通過消息隊列發送給receiver,直到用戶輸入“bye”爲止;最後,它向receiver進程發送消息“end”,並且等待receiver的應答,等到應答消息後,將接收到的應答信息顯示在終端屏幕上,刪除消息隊列,結束程序的運行。編寫receiver程序,它通過消息隊列接收來自sender的消息,將消息顯示在終端屏幕上,直至收到內容爲“end”的消息爲止,此時,它向sender發送一個應答消息“over”,結束程序的運行。
sender的代碼如下:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/stat.h>
#define MSG_FILE "sender.c"
#define BUFFER 255
#define PERM S_IRUSR|S_IWUSR
struct msgbuf
{
long mtype;
char mtext[BUFFER+1];
};
char message[BUFFER];
int main()
{
struct msgbuf msg;
key_t key;
int msgid;
int i;
//產生IPC對象的鍵值
if((key=ftok(MSG_FILE,67))==-1)
{
fprintf(stderr,"Creat Key Error:%s \n",strerror(errno));
exit(EXIT_FAILURE);
}
//創建消息隊列
if((msgid=msgget(key,PERM|IPC_CREAT))==-1)
{
fprintf(stderr,"Creat MessageQueue Error:%s \n",strerror(errno));
exit(EXIT_FAILURE);
}
msg.mtype=1;
//循環接受用戶輸入
while(1)
{
scanf("%s",message);
//如果用戶輸入bye,則發送end給receiver
if(strcmp(message,"bye")==0) {
strncpy(msg.mtext,"end",BUFFER);
msgsnd(msgid,&msg,sizeof(struct msgbuf),0);
break;
} else {
strncpy(msg.mtext,message,BUFFER);
}
msgsnd(msgid,&msg,sizeof(struct msgbuf),0);
}
// memset(&msg,'\0',sizeof(struct msgbuf));
//接收msg.mtype=2的消息,就是從receiver發來的消息
msgrcv(msgid,&msg,sizeof(struct msgbuf),2,0);
printf("Sender receive: %s\n",msg.mtext);
//刪除消息隊列
if(msgctl(msgid, IPC_RMID, 0) == -1)
{
fprintf(stderr, "Remove MessageQueue Error%s \n",strerror(errno));
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
receiver的代碼如下:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/stat.h>
#include <sys/msg.h>
#define MSG_FILE "sender.c"
#define BUFFER 255
#define PERM S_IRUSR|S_IWUSR
struct msgbuf
{
long mtype;
char mtext[BUFFER+1];
};
int main()
{
struct msgbuf msg;
key_t key;
int msgid;
int i;
char *myask="over";
//通過proj_id 67將sender和receiver關聯起來,兩者產生的key值是一樣的
if((key=ftok(MSG_FILE,67))==-1)
{
fprintf(stderr,"Creat Key Error:%s \n",strerror(errno));
exit(EXIT_FAILURE);
}
if((msgid=msgget(key,PERM|IPC_CREAT))==-1)
{
fprintf(stderr,"Creat MessageQueue Error:%s \n",strerror(errno));
exit(EXIT_FAILURE);
}
//等待接收來自sender的消息,當接受到end時推出,接下去發送over給sender
while(1)
{
msgrcv(msgid,&msg,sizeof(struct msgbuf),1,0);
printf("Receiver receive: %s\n",msg.mtext);
if(strcmp(msg.mtext,"end")==0)
{
break;
}
}
//發送over給sender
msg.mtype=2;
strncpy(msg.mtext,myask,BUFFER);
msgsnd(msgid,&msg,sizeof(struct msgbuf),0);
exit(EXIT_SUCCESS);
}