消息队列 进程通信

参考地址:http://www.linuxidc.com/Linux/2011-08/39738.htm

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define BUFSZ 512
struct message{ //消息结构体
long msg_type;
char msg_text[BUFSZ];
};

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

if((key=ftok(".",'a'))==-1) //ftok获得一个key
{
perror("ftok");
exit(1);
}
if((qid=msgget(key,IPC_CREAT|0666))==-1){ //创建一个消息队列
perror("msgget");
exit(1);
}
printf("opened queue %d\n",qid);
puts("Please enter the message to queue:");
if((fgets(msg.msg_text,BUFSZ,stdin))==NULL) // 从标准输入获取输入
{
puts("no message");
exit(1);
}
msg.msg_type = getpid();
len = strlen(msg.msg_text);
if((msgsnd(qid,&msg,len,0))<0){ //发送消息
perror("message posted");
exit(1);
}
if(msgrcv(qid,&msg,BUFSZ,0,0)<0){ //接收消息
perror("msgrcv");
exit(1);
}
printf("message is:%s\n",(&msg)->msg_text);
if((msgctl(qid,IPC_RMID,NULL))<0){ //删除消息
perror("msgctl");
exit(1);
}
exit(0);
}



posted @ 2011-12-14 14:46  wangkangluo1  阅读(284)  评论(0编辑  收藏  举报