Linux-消息队列

进程通信

Posted by Kingtous on September 6, 2019

利用消息队列机制实现进程之间的通信

打开或创建消息队列对象

int msgget(key_t key, int msgflg)

从消息队列接收消息

int msgrcv(int msqid, struct msgbuf *msgp, int msgsz, long msgtyp, int msgflg);

向消息队列发送消息

int msgsnd(int msqid, struct msgbuf *msgp, int msgsz, int msgflg);

消息队列控制操作

msgctl(int msqid, int cmd, struct msqid_ds *buf );

消息发送方:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <unistd.h>

struct msg_st
{
    long int msg_type;
    char text[1024];
};

int main(){

    int running = 1;
    struct msg_st data;
    char buffer[1024];
    int msgid = -1 ;
    msgid = msgget((key_t)1234,0666 | IPC_CREAT);
    if (msgid==-1)
    {
        fprintf(stderr,"msgget error.");
        exit(-1);
    }
    while (running){
        printf("Enter your message:");
        fgets(buffer,1024,stdin);
        data.msg_type=1;
        strcpy(data.text,buffer);
        if(msgsnd(msgid, (void *)&data,1024,0) == -1){
            fprintf(stderr,"message send failed.\n");
            exit(-1);
        }
        if(strncmp(buffer,"quit",4) == 0){
            running = 0;
            sleep(1);
        }
    }
    exit(0);
    return 0;
}

消息接收方:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <unistd.h>

struct msg_st
{
    long int msg_type;
    char text[1024];
};


int main(){

    int running = 1;
    struct msg_st data;
    char buffer[1024];
    int msgid = -1 ;
    long int msgtype = 0;
    msgid = msgget((key_t)1234,0666 | IPC_CREAT);
    if (msgid==-1)
    {
        fprintf(stderr,"msgget error.");
        exit(-1);
    }
    while (running){
        if(msgrcv(msgid,(void*)&data,1024,msgtype,0)==-1){
            fprintf(stderr,"get message failed with error\n");
            exit(-1);
        }
        printf("Message Get:%s\n",data.text);
        if(strncmp(data.text,"quit",4)==0){
            running = 0;
        }
    }
    if(msgctl(msgid,IPC_RMID,0)==-1){
      	// 删除消息对列
        fprintf(stderr,"IPC_RMID Error.\n");
        exit(-1);
    }
    exit(0);
    return 0;
}

效果截图:

image-20190906101851941