1. 程式人生 > >posix message queue測試

posix message queue測試

2010-11-18

周海漢 2010.11.18

原始碼:

//////////////////////////////////////////
//author 	zhouhh
//date 		2010.11.18
//notes
//history
//copyright( 2010 ) allright reserved!
/////////////////////////////////////////

#include
#include
#include
#include
#include
#include
 #include
//       mqd_t mq_open(const char *name, int oflag);
//       mqd_t mq_open(const char *name, int oflag, mode_t mode,
//                     struct mq_attr *attr);
#define _XOPEN_SOURCE 600
#define FILE_MODE (S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)
void main(void)
{
    mqd_t mqdes = mq_open("testmymq",O_RDWR|O_CREAT, FILE_MODE,NULL);
    if( mqdes == (mqd_t) -1)
    {
        perror("mq_open error");
    }

    struct sigevent se;
    //se.sigev_notify = SIGEV_SIGNAL;
    //se.sigev_signo =
    char buf[1024];
    size_t msg_len = 1024;
    const struct timespec abs_timeout = {1000,0};//* seconds *//* nanoseconds */
    int i = 0;
    for( i = 0; i < 10; i++)
    {
        //ssize_t mqsize =  mq_timedreceive( mqdes, buf,  msg_len, NULL, &abs_timeout);
        ssize_t mqsize =  mq_receive( mqdes, buf,  msg_len, NULL);
        if( mqsize < 0 )
        {
            if(errno == EAGAIN)
            {
                printf("the mq is empty and nonblockn");
            //printf("timeout n");
            }

            printf("timeout n");
            continue;
        }
        printf("received msg:%sn",buf);
    }
}

編譯,注意-lrt引數: $gcc -o testmsg -lrt testmqs.c 執行:

[email protected]:~/sms$ ./testmsg
mq_open error: Invalid argument

修改mq_open行為

mqd_t mqdes = mq_open(“/home/zhouhh/testmymq”,O_RDWR O_CREAT, FILE_MODE,NULL);

編譯執行: [email protected]:~/sms$ ./testmsg mq_open error: No such file or directory

man 7 mq_review 說要在前面加“/”,但mq的名字不要再有其他的“/”。 修改mq_open行為

mqd_t mqdes = mq_open(“/testmymq”,O_RDWR O_CREAT, FILE_MODE,NULL);

編譯執行:

[email protected]:~/sms$ ./testmsg mq_open error: Permission denied

mqueue的大多數錯誤都被我碰到了。

根據高人指點,新建/dev/mqueue目錄,將mqueue型別的none mount到/dev/mqueue:

[email protected]:/dev$ sudo mkdir mqueue
[email protected]:/dev$ sudo mount -t mqueue none /dev/mqueue

執行: [email protected]:~/sms$ ./testmsg 成功(但mq_receive並沒有阻塞)。 [email protected]:/dev/mqueue$ ls testmymq

如非註明轉載, 均為原創. 本站遵循知識共享CC協議,轉載請註明來源