Linux IPC 之消息队列

System V  or  POSIX ?

该使用哪个呢, 这是个问题 ...

相对而言,我更倾向于后者 posix mq

posix mq 的概况看这里:man mq_overview

简单的实现代码:

#include <mqueue.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

#define MY_MQ_NAME "/my_test_mq"
#define MSG_LEN 8192
struct my_msg
{
    unsigned int msg_type;
    char msg_date[MSG_LEN];
};

int main(int argc, char ** argv)
{
    unsigned int prio;
    struct my_msg msg;
    struct mq_attr attr;
    ssize_t mq_ret;
    char mq_msg[MSG_LEN];
    mqd_t mqd;

    // creat
    attr.mq_maxmsg = 40960;
    attr.mq_msgsize = MSG_LEN;
    mqd = mq_open(MY_MQ_NAME, O_RDWR|O_CREAT, S_IRWXU|S_IRWXG, &attr);
    if(mqd < 0)
    {
        perror("mq_open error");
        return -1;
    }

    //get attribute
    mq_ret = mq_getattr(mqd, &attr);
    if(mq_ret == -1)
    {
        perror("mq_getattr");
        mq_close(mqd);
        exit(1);
    }
    printf("max #msgs=%ld, max #bytes/msg=%ld, current msg =%ld\n",\
            attr.mq_maxmsg,attr.mq_msgsize,attr.mq_curmsgs);

    //reveive msg
    while(1)
    {
        mq_ret = mq_receive(mqd, mq_msg, sizeof(mq_msg), NULL);
        printf("%s\n",mq_msg);
        if(mq_ret == -1)
        {
            perror("mq_receive error");
            mq_close(mqd);
            break;
        }
        usleep(32);
    }

    mq_close(mqd);

    return 0;
}


发送消息代码:

int main(int argc, char **argv)
{
    int mq_ret;
    mqd_t mqd;
    size_t len;
    char *ptr;
    unsigned int prio;

    prio = 0;
    ptr = (char*)malloc(MSG_LEN);
    if(ptr == NULL)
    {
        perror("malloc ptr error");
        return -1;
    }
    strcpy(ptr,"Hello mqueue, I am who you do not know !");

    mqd = mq_open(MY_MQ_NAME, O_WRONLY);
    if(mqd == -1)
    {
        perror("mq_open error");
        return -1;
    }

    while(1)
    {
        mq_ret = mq_send(mqd, ptr, MSG_LEN, prio);
        if(mq_ret == -1)
        {
            perror("mq_send error");
            mq_close(mqd);
            break;
        }
        usleep(2);
    }
    return 0;
}


另外, Linux 系统中POSIX mq 的大小限制查看及设置命令:

# ulimit -q

当然也可以在程序中设置:

    struct rlimit new_rlimit;
    new_rlimit.rlim_cur = NEW_MQ_MEM_LIMIT;
    new_rlimit.rlim_max = NEW_MQ_MEM_LIMIT;
    if (setrlimit(RLIMIT_MSGQUEUE, &new_rlimit) != 0)
     {
         perror("Failed BUG exploit! setrlimit() didn't return success");
        return EXIT_FAILURE;
     }





参考:

http://www.cnblogs.com/polestar/archive/2012/4/16.html

你可能感兴趣的:(linux,linux,linux,Queue,Queue,ipc,ipc,posix,posix)