Chinaunix首页 | 论坛 | 博客
  • 博客访问: 252275
  • 博文数量: 65
  • 博客积分: 2525
  • 博客等级: 少校
  • 技术积分: 740
  • 用 户 组: 普通用户
  • 注册时间: 2009-04-01 23:46
文章分类
文章存档

2010年(13)

2009年(52)

我的朋友

分类: LINUX

2010-01-19 09:53:41

发端:
 

#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>

#define MAX_TEXT 512
struct my_msg_st //临时消息结构

{
    int my_msg_type;
    char msg_text[MAX_TEXT]; //自己修改了存储消息的空间大小

};

int main(int argc,char *argv[])
{
    int running=1;
    struct my_msg_st some_data;
    int msgid;
    char buffer[BUFSIZ];

    if((msgid=msgget((key_t)12345,0666|IPC_CREAT))==-1) //创建消息队列

    {
        perror("msgget");
        exit(EXIT_FAILURE);
    }

    while(running)
    {
        printf("Enter the mssage to send:");
        fgets(buffer,BUFSIZ,stdin); //读取信息

        some_data.my_msg_type=1; //设置类型为 1

        strcpy(some_data.msg_text,buffer);//复制消息


        if((msgsnd(msgid,(void *)&some_data,MAX_TEXT,0))==-1) //发送消息

        {
            perror("msgsnd");
            exit(EXIT_FAILURE);
        }
        if(strncmp(buffer,"end",3)==0)//判断是否为结束消息

        {
            running=0;
        }
    }
    return 0;
}


收端

#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
struct my_msg_st
{
    int my_msg_type;
    char msg_text[BUFSIZ];
};
int main(int argc,char *argv[])
{
    int running=1;
    int msgid;
    struct my_msg_st some_data;
    int msg_to_receive=0; //类型设置为 0,可以接受任何消息类型的消息


    if((msgid=msgget((key_t)12345,0666 | IPC_CREAT))==-1) //消息队列标识要一致

    {
        perror("msgget");
        exit(EXIT_FAILURE);
    }

    while(running)
    {
        if(msgrcv(msgid,(void *)&some_data,BUFSIZ,msg_to_receive,0)==-1)//接收消息

        {
            perror("msgrcv");
            exit(EXIT_FAILURE);
        }
        printf("receiver mssage:%s",some_data.msg_text);
        if(strncmp(some_data.msg_text,"end",3)==0)
        running=0;
    }

    if(msgctl(msgid,IPC_RMID,0)==-1) //删除消息队列

    {
        fprintf(stderr,"msgctl(IPC_RMID) failed\n");
        exit(EXIT_FAILURE);
    }
    return 0;
}



可以用ipcs -q 查看
阅读(1068) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~