使用消息队列实现进程间的通信(代码实例)

分别编写代表两个人的程序,他们之间用消息队列进行通信,注意箭头是双向的!注意: 1. Jack与Rose必须可以同时收与发 2. Jack发送了“quit”给对方,自己与Rose都要退出 3. Rose发送了”quit”给对方,,自己与Jack都要退出

信息
信息
Jack
Rose

什么是消息队列?

**消息队列是一种进程间通信的方式,是IPC对象的一种,使用前需要申请对应的资源(key值与ID号)。
消息队列使用特定的函数:msgsnd(),msgrcv() 来收发数据,可以读取特定的数据。
消息队列数据有以下特点:
1.消息队列的数据都包括"标识+正文"。
2.往消息队列中写入数据时,必须提供"标识+正文"
3.从消息队列中读取数据时,必须提供想读取的标识
数据:
struct data
{
long mtype; //消息的标识,必须是long类型
char mtext[1]; //消息的正文,可以是任意类型,且大小自定
};
消息队列有以下接口:
//1.根据key值申请消息队列ID号
int msgget(key_t key, int msgflg);
//2.向消息队列发送数据
int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);
//3. 从消息队列中读取数据
ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp,
int msgflg);
//4.设置或获取消息队列的相关属性
int msgctl(int msqid, int cmd, struct msqid_ds *buf);
**
//Jack.c

//实现与rose的相互通信
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <errno.h>
#include <unistd.h>
#include <signal.h>
#include <wait.h>

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

//定义消息结构体
struct msgbuf
{
        long mtype;
    	char mtext[64];
};

int main(int argc, char *argv[])
{
   //定义key值
    key_t key;
    key = ftok(".", 10);
    
    //根据key值申请消息队列ID号
    int msgid;
    msgid = msgget(key , IPC_CREAT|0666);
    
    struct msgbuf buf;
    
    pid_t pid = fork();
    //父进程持续发信息
    if(pid > 0)
    {
        printf("I'm Jack.\n");
        while(1)
        {
            memset(buf.mtext,0,sizeof(buf.mtext));
            //写标识是1的信息进队列
            buf.mtype = 1;

            fgets(buf.mtext,64,stdin);

            msgsnd(msgid,&buf,strlen(buf.mtext),0);
            //发送quit后,杀掉子进程,之后退出
            if(strncmp(buf.mtext,"quit",4) == 0)
            {
                kill(pid,SIGKILL);
                break;
            }
        }
        wait(NULL);
    }
    //子进程持续读信息
    if(pid == 0)
    {
        while(1)
        {
            memset(buf.mtext,0,sizeof(buf.mtext));
            //从队列中读标识是2的信息
            msgrcv(msgid,&buf,64,2,0);

            printf("receive from rose:%s",buf.mtext);
            //收到quit,杀掉父进程,之后退出
            if(strncmp(buf.mtext,"quit",4) == 0)
            {
                kill(getppid(),SIGKILL);
                break;
            }
        }
    }
    //删除队列信息
    msgctl(msgid, IPC_RMID, NULL);
    return 0;
}

//Rose.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <errno.h>
#include <unistd.h>
#include <signal.h>
#include <wait.h>

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

//自定义消息结构体
struct msgbuf
{
        long mtype;
    char mtext[64];
};

int main(int argc, char *argv[])
{
   //定义key值
    key_t key;
    key = ftok(".", 10);
    
    //申请消息队列ID号
    int msgid;
    msgid = msgget(key , IPC_CREAT|0666);
    
    struct msgbuf buf;
    
    pid_t pid = fork();
    //父进程持续读信息
    if(pid > 0)
    {
        printf("I'm Rose.\n");
        while(1)
        {
            memset(buf.mtext,0,sizeof(buf.mtext));

            //从队列中读标识是1的信息
            msgrcv(msgid,&buf,64,1,0);

            printf("receive from jack:%s",buf.mtext);
            //收到quit后,杀掉子进程,之后退出
            if(strncmp(buf.mtext,"quit",4) == 0)
            {
                kill(pid,SIGKILL);
                break;
            }
        }
        wait(NULL);
    }
    //子进程持续发信息
    if(pid == 0)
    {
        while(1)
        {
            memset(buf.mtext,0,sizeof(buf.mtext));
            //写标识是2的信息进队列
            buf.mtype = 2;

            fgets(buf.mtext,64,stdin);

            msgsnd(msgid,&buf,strlen(buf.mtext),0);
            //发送quit后,杀掉父进程,之后退出
            if(strncmp(buf.mtext,"quit",4) == 0)
            {
                kill(getppid(),SIGKILL);
                break;
            }
        }
    }
    //删除队列消息
    msgctl(msgid, IPC_RMID, NULL);
    return 0;
}


//运行结果

进程间通信
从代码可以看出,Jack和Rose都从队列中得到自己想要获得的信息,没有混淆,靠的就是数据的标识。

使用消息队列很简单,但是使用这种方式进行进程间通信,效率是不高的,因为两个进程间的数据传递并不是直接的,而是经过内核的辗转努力的,因此不适用于传输海量数据,而共享内存可以解决这个问题。

//还在学习中,如有错误,欢迎指出,谢谢 (´・ᴗ・`)

  • 5
    点赞
  • 57
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是一个简单的示例代码,展示了如何在Linux进程使用消息队列进行通信。 发送方进程: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/msg.h> #define MSG_SIZE 256 struct msg_buffer { long msg_type; char msg_text[MSG_SIZE]; }; int main() { key_t key; int msg_id; struct msg_buffer message; // 创建一个唯一的key key = ftok("msgq.txt", 'A'); // 创建消息队列 msg_id = msgget(key, 0666 | IPC_CREAT); // 设置消息类型 message.msg_type = 1; // 设置消息内容 strcpy(message.msg_text, "Hello from sender!"); // 发送消息 msgsnd(msg_id, &message, sizeof(message), 0); printf("Message sent: %s\n", message.msg_text); return 0; } ``` 接收方进程: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/msg.h> #define MSG_SIZE 256 struct msg_buffer { long msg_type; char msg_text[MSG_SIZE]; }; int main() { key_t key; int msg_id; struct msg_buffer message; // 创建一个唯一的key key = ftok("msgq.txt", 'A'); // 获取消息队列 msg_id = msgget(key, 0666 | IPC_CREAT); // 接收消息 msgrcv(msg_id, &message, sizeof(message), 1, 0); printf("Message received: %s\n", message.msg_text); // 删除消息队列 msgctl(msg_id, IPC_RMID, NULL); return 0; } ``` 这两个进程可以在同一台计算机上运行,也可以在不同的计算机上运行。在发送方进程中,首先创建一个唯一的key,然后使用该key创建一个新的消息队列。接下来,设置消息类型为1,将消息内容设置为“Hello from sender!”,并将消息发送到消息队列中。 在接收方进程中,使用与发送方进程相同的key获取消息队列。然后使用msgrcv函数接收消息,并将消息类型设置为1,这与发送方进程中设置的消息类型相同。最后,打印接收到的消息,然后使用msgctl函数删除消息队列
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值