歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

簡單的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));
 */
}

Copyright © Linux教程網 All Rights Reserved