关于Unix第二卷60页的mq_open 函数的参数非法问题

来源:互联网 发布:网络直播间策划方案 编辑:程序博客网 时间:2024/05/21 12:29

utili.h文件:

#ifndef _UTILI_H
#define _UTILI_H


#include<stdio.h>
#include<unistd.h>
#include<errno.h>
#include<stdlib.h>
#include<assert.h>  
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<string.h>
#include<mqueue.h>
#include<wait.h>
#define MAXLEN 1024

#define FILE_MODE  (S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)

#endif

mqcreate.c 文件:

#include"../utili.h"



int main(int argc,char **argv)
{
    int c,flags;
    mqd_t mqd;

    flags = O_RDWR|O_CREAT;
    while((c=getopt(argc,argv,"e"))!=-1)
    {
        switch(c)
        {
            case 'e':
            flags |= O_EXCL;
            break;
        }
    }
    if(optind != argc-1)
    {
        printf("usage:mqcreate [-e] <name>");
        exit(0);
    }
    mqd = mq_open(argv[optind],flags,FILE_MODE,NULL);
    if(mqd == -1)
    printf("mq_opem Fail. errno = %d\n",errno);
    assert(mqd!=-1);

    mq_close(mqd);
    exit(0);
}


编译的时候:  gcc -o mqcreate   mqcreate.c  -lrt

如果编译出错执行以下两条命令:

           # mkdir /dev/mqueue
           # mount -t mqueue none /dev/mqueue
原因是:在Linux系统,消息队列是创建在虚拟文件系统上,而虚拟文件需要挂载

编译通过后  执行:  ./mqcreate  /mq_name

需要注意的是命令行参数的 /mq_name   必须以这种格式: /mq_name

原因是:每一个消息队列是有一个name来定义的,即是以空字符结尾的字符串形如: /somename

这么命名,原因详细参见Unix第二卷的14页  2.2节 IPC名字:这一小节详细阐述了IPC 名字的规则和移植性问题.

如果还有问题请仔细阅读:  man  7 mq_overview






阅读全文
0 0