LEVEL5DAY6作业 编写一个程序,实现两个程序使用消息队列通信。

写消息队列程序

#include <cstdio>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <unistd.h>

char* path = "./";
char* botton = "Message List test success!\n";
typedef  struct {
    long mtype;
    char mtext[64];
} MSG;
#define LEN (sizeof(MSG) - sizeof(long))

int main()
{
    int result,id;
    MSG buf;
    key_t key = ftok(path, 75);
    if (key == EOF) {
        perror("ftok");
        return -1;
    }

    id = msgget(key, IPC_CREAT | 0666);
    if (id == EOF) {
        perror("msgget");
        return -1;
    }

    buf.mtype = 100;
    strcpy(buf.mtext, botton);
    result = msgsnd(id, &buf, LEN, 0);
    if (result == EOF) {
        perror("msgsnd");
        return -1;
    }
    sleep(10);
    msgctl(id, IPC_RMID, NULL);
    return 0;
}

读消息队列程序

#include <cstdio>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <unistd.h>

char* path = "./";
char* botton = "Message List test success!\n";
typedef  struct {
    long mtype;
    char mtext[64];
} MSG;
#define LEN (sizeof(MSG) - sizeof(long))

int main()
{
    int result,id;
    MSG buf;
    key_t key = ftok(path, 75);
    if (key == EOF) {
        perror("ftok");
        return -1;
    }
    id = msgget(key, IPC_CREAT | 0666);

    if (id == EOF) {
        perror("msgget");
        return -1;
    }
    buf.mtype = 100;
	result = msgrcv(id,&buf,LEN,0,0);
    
    if (result == EOF) {
        perror("msgrcv");
        return -1;
    }
	printf("%s\n",buf.mtext);


    sleep(10);
    msgctl(id, IPC_RMID, NULL);
    return 0;
}