您的位置:首页 > 其它

4、进程间通信-消息队列IPC

2010-11-30 14:28 183 查看
1、创建一个消息队列,然后使用msgctl函数读取相关信息,单进程

code:

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<string.h>
#include<sys/msg.h>
#define BUFSIZE 128
// 自定义消息结构体
struct msg_buf
{
long type;
char msg[BUFSIZE];
};
int main()
{
key_t key;
int msgid;
struct msg_buf msg_snd,msg_rcv;
char * ptr="hello world";
memset(&msg_snd,'/0',sizeof(struct msg_buf));
memset(&msg_rcv,'/0',sizeof(struct msg_buf));
msg_snd.type=1;
msg_rcv.type=1;
memcpy(msg_snd.msg,ptr,strlen(ptr));
// 获得key
key=ftok(".",'A');
if(key==-1){
perror("ftok");
exit(EXIT_FAILURE);
}

// 通过key,创建信息队列
msgid=msgget(key,0600|IPC_CREAT);
if(msgid==-1){
perror("msgget");
exit(EXIT_FAILURE);
}
// 发送消息
int res=msgsnd(msgid,(void *)&msg_snd,strlen(msg_snd.msg),0);
printf("res is %d/n",res);
// 读取消息队列基本信息
struct msginfo info;
msgctl(msgid,MSG_INFO,&info);
printf("buf.msgmax=%d/n",info.msgmax);

// 读取消息
msgrcv(msgid,(void*)&msg_rcv,BUFSIZE,msg_rcv.type,0);
printf("rev msg:%s/n",msg_rcv.msg);
// 删除队列
msgctl(msgid,IPC_RMID,0);
}


结果:

root@ubuntu:/code/chap9# ./run1

res is 0

buf.msgmax=8192

rev msg:hello world

2、使用消息队列实现实时通信(注:阻塞的)。可以考虑实现双向的基于类型的、非阻塞方式的双向数据传递

code:

发送端代码:

#include<stdlib.h>
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#define MAX_TEXT 512
struct my_msg_st
{
int my_msg_type;
char msg_text[MAX_TEXT];
};
int main()
{
int msgid=msgget((key_t)12345,0666|IPC_CREAT);
if(msgid==-1){
perror("msgget");
exit(EXIT_FAILURE);
}
int running =1;
char buffer[BUFSIZ];
struct my_msg_st some_data;
while(running)
{
printf("enter/n");
fgets(buffer,BUFSIZ,stdin);
some_data.my_msg_type=1;
strcpy(some_data.msg_text,buffer);
int re=msgsnd(msgid,(void*)&some_data,MAX_TEXT,0);
if(re==-1){
perror("msgsnd");
exit(EXIT_FAILURE);
}
if(strncmp(buffer,"end",3)==0)
running =0;
}
return 0;
}


接受端代码:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
struct my_msg_st
{
int my_msg_type;
char msg_text[BUFSIZ];
};
int main()
{
int msgid=msgget((key_t)12345,0666|IPC_CREAT);
if(msgid==-1){
perror("msgget");
exit(EXIT_FAILURE);
}
struct my_msg_st some_data;
int running=1;
while(running)
{
int re=msgrcv(msgid,(void*)&some_data,BUFSIZ,0,0);
if(re==-1){
perror("msgrcv");
exit(EXIT_FAILURE);
}
printf("rcv:%s/n",some_data.msg_text);
if(strncmp(some_data.msg_text,"end",3)==0)
running =0;
}

int re=msgctl(msgid,IPC_RMID,0);
if(re==-1){
perror("close");
exit(EXIT_FAILURE);
}
return 0;
}


结果:

发送端:

root@ubuntu:/code/chap9# ./run2

enter

Jason

enter

Liu

enter

end

接受端:

root@ubuntu:/code/chap9# ./run2_o

rcv:Jason

rcv:Liu

rcv:end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: