消息队列的范例代码

随机生成键值(不重复)用 ftok

发送端代码
#include
#include
#include
#include

struct msgt
{
    long msgtype;
    char text[1024];
};

void main()
{
    int key;
    int msqid;
    int k;
    struct msgt mymsg;
     
    key = ftok("/home/kaito/mark_try/", 4869);
     
    msqid = msgget(key, IPC_CREAT);
     
    while(1)
    {
    printf("please input the type of the queue(0 to quit):");
    scanf("%d", &k);
   
    if(k == 0)
        break;
   
    printf("input the data:");
   
    scanf("%s", mymsg.text);
   
    msgsnd(msqid, &mymsg, sizeof(struct msgt), 0);
    }
     
    msgctl(msqid, IPC_RMID, 0);
}




接收端代码
#include
#include
#include
#include

struct msgt
{
    long msgtype;
    char text[1024];
};

void main()
{
    int key;
    int msqid;
    struct msgt kmsg;
     
    key = ftok("/home/kaito/mark_try/", 4869);
     
    msqid = msgget(key, IPC_EXCL);
     
    while(1)
    {
        msgrcv(msqid, &kmsg, sizeof(struct msgt), 0, 0);
     
        printf("the received text is :%s\n", kmsg.text);
    }
}

版权声明:本文为weixin_39162701原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。