您的位置:首页 > 其它

消息队列的发送与接收.

2011-09-02 19:40 429 查看
//消息队列的发送操作
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<errno.h>
#include<string.h>

struct message
{
long msg_type;
char txt[50];
};

int main(void)
{
key_t key;
int qid;
struct message msg;

key = ftok(".",'a');

if((qid = msgget(key,IPC_CREAT|0600)) < 0)
perror("msgget");
else
printf("make msg success qid");

int n = 10;
while(n--){
if((msgrcv(qid,&msg,sizeof(msg),200,0)) < 0)
perror("msgrcv");
else
printf("rcv message:%s\n",msg.txt);
memset(msg.txt,0,sizeof(msg.txt));

}
if(msgctl(qid,IPC_RMID,NULL) < 0)
perror("msgctl");
else
printf("delete msg success\n");

return(0);
}


//消息队列的接收

#include<stdio.h>#include<stdlib.h>#include<unistd.h>#include<sys/types.h>#include<sys/ipc.h>#include<sys/msg.h>#include<errno.h>#include<string.h>struct message{long msg_type;char txt[50];};int main(void){key_t key ;int qid;struct message msg[10];key = ftok(".",'a');if((qid
= msgget(key,IPC_CREAT|0600)) < 0)perror("msgget");elseprintf("make msg success qid = %d\n",qid);int i = 10;while(i--){msg[i].msg_type = 200;strcpy(msg[i].txt," message....");if(msgsnd(qid,&msg[i],sizeof(struct message),0) < 0)perror("msgsnd");elseprintf("add
message success\n");}return 0;}

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