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

题目: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
", msg.mtext);
        }

}



int main(int argc, char **argv)
{
        if (argc != 2 ||
                (strcmp(argv[1], "r") && strcmp(argv[1], "s")))
        {
                printf("Usage: %s [ r | s ]
", argv[0]);
                printf("	 r:receive message queue
");
                printf("	 s:send message queue
");
                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;
}

  

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