• 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

linux c 消息队列实例代码示范

Linux 水墨上仙 2500次浏览

消息队列是一系列连续排列的消息,保存在内核中,通过消息队列的引用标识符来访问。消息队列与管道很相似,但使用消息队列的好处是对每个消息指定了特定消息类型,接收消息的进程可以请求接收下一条消息,也可以请求接收下一条特定类型的消息。
来源:http://blog.csdn.net/muge0913/article/details/7342907

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <string.h>
int main()
{
    key_t unique_key;
    int msgid;
    
    int status;
    char str1[]={"test message:hello muge0913"};
    char str2[]={"test message:goodbye muge0913"};
    
    struct msgbuf
    {
    long msgtype;
    char msgtext[1024];
    }sndmsg,rcvmsg;
    if((msgid = msgget(IPC_PRIVATE,0666))==-1)
    {
    printf("msgget error!\n");
    exit(1);
    }
    sndmsg.msgtype =111;
    sprintf(sndmsg.msgtext,str1);
    if(msgsnd(msgid,(struct msgbuf *)&sndmsg,sizeof(str1)+1,0)==-1)
    {
    printf("msgsnd error!\n");
    exit(1);
    }
    sndmsg.msgtype =222;
    sprintf(sndmsg.msgtext,str2);
    if(msgsnd(msgid,(struct msgbuf *)&sndmsg,sizeof(str2)+1,0)==-1)
    {
    printf("msgsnd error\n");
    exit(1);
    }
    if((status = msgrcv(msgid,(struct msgbuf *)&rcvmsg,80,222,IPC_NOWAIT))==-1)
    {
    printf("msgrcv error\n");
    exit(1);
    }
    printf("The receved message:%s\n",rcvmsg.msgtext);
    msgctl(msgid,IPC_RMID,0);
    exit(0);
}


喜欢 (0)
加载中……