码迷,mamicode.com
首页 > 其他好文 > 详细

自测之Lesson11:消息和消息队列

时间:2018-03-11 00:24:44      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:memset   自测   str   include   pos   less   scan   发送消息   进程创建   

题目:key及ftok函数的作用。

 

解答:

key是用来创建消息队列的一个参数,当两个key相同时,创建消息队列会引起“误会”(除非有意为之)。所以我们可以通过ftok函数来获得一个“不易重复”的key。

key对于进程间通信也有帮助,当一进程知晓另一进程创建消息队列所用的key后,便可以使用该key访问该消息队列。

 

 

题目:编写一个可以向消息队列发送消息和接收消息的程序。

 

实现代码:

#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>

struct msgbuf {                         // msgbuf结构体
        long mtype;
        char mtext[1024];    
};


void TestMsgSend(int msqid)
{
        while(1) {
                long msgType;
                struct msgbuf msg;
                fprintf(stderr, "Send[FORMAT:type msg]:");
                scanf("%ld%s", &msgType, msg.mtext);
                msg.mtype = msgType;
                int iRet = msgsnd(msqid, &msg, strlen(msg.mtext), 0); 
                if (iRet == -1) {
                        perror("fail msgsnd");
                        return;
                }    
        }
}

void TestMsgRecv(int msqid)
{
        struct msgbuf msg;
        long msgType;
        while (1) {
                fprintf(stderr, "Recv[FORMAT:type]:");
                scanf("%ld", &msgType);
                memset(msg.mtext, 0, 1024);
                msg.mtype = msgType;
                int iRet = msgrcv(msqid, &msg, 1024, msg.mtype, 0);
                if (iRet < 0) {
                        perror ("fail magrcv");
                        return;
                }
                printf("Recv:%s\n", msg.mtext);
        }

}



int main(int argc, char **argv)
{
        if (argc != 2 ||
                (strcmp(argv[1], "r") && strcmp(argv[1], "s")))
        {
                printf("Usage: %s [ r | s ]\n", argv[0]);
                printf("\t r:receive message queue\n");
                printf("\t s:send message queue\n");
                return 0;
        }
        key_t key;
        key = ftok("test1", 1);                 // 创建key
        if (key == -1) {
                perror("fail ftok");
                return -1;
        }
        int msqid;
        msqid = msgget(key, IPC_CREAT | 0664);  // 创建消息队列
        if (msqid == -1) {
                perror("fail msgget");
                return -1;
        }

        if (argv[1][0] == ‘s‘) {                // 进程1向消息队列发送消息
                TestMsgSend(msqid);
        }
        else if (argv[1][0] == ‘r‘) {           // 进程2从消息队列读取消息
                TestMsgRecv(msqid);
        }

        return 0;
}

 

  

 

自测之Lesson11:消息和消息队列

标签:memset   自测   str   include   pos   less   scan   发送消息   进程创建   

原文地址:https://www.cnblogs.com/xzxl/p/8542194.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!