美文网首页
linux c POSIX消息队列示例

linux c POSIX消息队列示例

作者: 一路向后 | 来源:发表于2021-08-29 21:30 被阅读0次

    1.源码实现

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <malloc.h>
    #include <unistd.h>
    #include <fcntl.h>
    #include <mqueue.h>
    #include <errno.h>
    
    int main()
    {
        mqd_t mqid;
        char *msg = "yuki";
        int i;
    
        mqid = mq_open("/1.que", O_RDWR|O_CREAT|O_EXCL, 0666, NULL);
        if(mqid < 0)
        {
            if(errno == EEXIST)
            {
                mq_unlink("/1.que");
                mqid = mq_open("/1.que", O_RDWR|O_CREAT|O_EXCL, 0666, NULL);
            }
            else
            {
                perror("open message queue error...");
                return -1;
            }
        }
    
        if(fork() == 0)
        {
            struct mq_attr mqattr;
            char *buf = NULL;
    
            mq_getattr(mqid, &mqattr);
    
            buf = (char *)malloc(mqattr.mq_msgsize);
    
            for(i=0; i<5; i++)
            {
                if(mq_receive(mqid, buf, mqattr.mq_msgsize, NULL) < 0)
                {
                    perror("receive message failed...");
                    continue;
                }
    
                printf("receive message %d: %s\n", i+1, buf);
            }
    
            free(buf);
    
            exit(0);
        }
    
        for(i=0; i<5; i++)
        {
            if(mq_send(mqid, msg, sizeof(msg), i) < 0)
            {
                perror("send message");
                continue;
            }
    
            printf("send message %d: %s successful\n", i+1, msg);
    
            sleep(1);
        }
    
        return 0;
    }
    

    2.编译源码

    $ gcc -o test test.c -lrt
    

    3.运行及其结果

    $ ./test
    send message 1: yuki successful
    receive message 1: yuki
    send message 2: yuki successful
    receive message 2: yuki
    send message 3: yuki successful
    receive message 3: yuki
    send message 4: yuki successful
    receive message 4: yuki
    send message 5: yuki successful
    receive message 5: yuki
    

    相关文章

      网友评论

          本文标题:linux c POSIX消息队列示例

          本文链接:https://www.haomeiwen.com/subject/hmmgiltx.html