简单的Linux 消息队列测试代码

简单的Linux 消息队列测试代码:

/*msg_block_read.c*/

#include <sys/types.h>
#include <sys/msg.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
 
 
struct msg_buf
{
    int mtype;
//    char aaa[255];   //此结构体只能包含两个成员
    char data[255];
};
 
int main()
{
        key_t key;
        int msgid;
        int ret;
        struct msg_buf msgbuf;
 
        key=ftok("/tmp/2",'a');
        printf("key =[%x]\n",key);
        msgid=msgget(key,IPC_CREAT|0666); /*Íš¹ýÎÄŒþ¶ÔÓŠ*/
 
        if(msgid==-1)
        {
                printf("create error\n");
                return -1;
        }
/* 
        msgbuf.mtype = getpid();
        strcpy(msgbuf.data,"test haha, aaaaaaaaaaaaaaaaaa");
        ret=msgsnd(msgid,&msgbuf,strlen(msgbuf.data),0);
        if(ret==-1)
        {
                printf("send message err\n");
                return -1;
        }
 */
        memset(&msgbuf,0,sizeof(msgbuf));
        ret=msgrcv(msgid,&msgbuf,sizeof(msgbuf.data),0,0); //阻塞读取,第一个消息
        if(ret==-1)
        {
                printf("recv message err\n");
                return -1;
        }
        printf("recv msg =[%s], len = %d\n",msgbuf.data, strlen(msgbuf.data));
 
}

/*msg_block_write.c*/

#include <sys/types.h>
#include <sys/msg.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
 
 
struct msg_buf
{
    int mtype;
//    char aaa[255];  //此结构体只能包含两个成员
    char data[255];
};
 
int main()
{
        key_t key;
        int msgid;
        int ret;
        struct msg_buf msgbuf;
 
        key=ftok("/tmp/2",'a');
        printf("key =[%x]\n",key);
        msgid=msgget(key,IPC_CREAT|0666); /*Íš¹ýÎÄŒþ¶ÔÓŠ*/
 
        if(msgid==-1)
        {
                printf("create error\n");
                return -1;
        }
 
        msgbuf.mtype = getpid();
        strcpy(msgbuf.data,"test haha, aaaaaaaaaaaaaaaaaa");
        ret=msgsnd(msgid,&msgbuf,strlen(msgbuf.data),0); // 阻塞发送
        if(ret==-1)
        {
                printf("send message err\n");
                return -1;
        }
/* 
        memset(&msgbuf,0,sizeof(msgbuf));
        ret=msgrcv(msgid,&msgbuf,sizeof(msgbuf.data),getpid(),0);
        if(ret==-1)
        {
                printf("recv message err\n");
                return -1;
        }
        printf("recv msg =[%s], len = %d\n",msgbuf.data, strlen(msgbuf.data));
 */
}

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/pxjjy.html