使用消息队列实现两进程间实时通信的例子

该博客介绍了一个使用消息队列实现的简单两进程间实时通信的例子。通过发送端发送数据,接收端接收数据,当发送端输入'end'时,双方程序退出。代码中包含了发送端和接收端的C语言实现,并展示了如何创建消息队列、发送和接收消息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

      由发送端和接收端组成,这里只是实现了发送端发送接收端接收,相当于半双工吧。编译,运行,发送端输入的数据将会在接收端显示出来,当在发送端输入end之后,发送端和接收端都会退出程序。可以使用ipcs -q命令查看系统中的信号量的状态

发送端源代码

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <sys/msg.h>
#define MAX_TEXT 512

struct my_msg_st
{
 int my_msg_type;
 char msg_text[MAX_TEXT];
};
typedef struct my_msg_st  MSG_ST;

int main()
{
 int msgid;
 unsigned char running=1;
 char buff[MAX_TEXT];
 MSG_ST  sendmsg;
 
 msgid=msgget((key_t)12345,0777|IPC_CREAT);
 if(msgid==-1)
 {
  perror("msgget");
  exit(1);
 }
 while(running)
 {
  memset(&sendmsg,0,sizeof(MSG_ST));
  printf("please int msg:");
  fgets(buff,MAX_TEXT,stdin);
  sendmsg.my_msg_type =1;
  strcpy(sendmsg.msg_text,buff);
  if(msgsnd(msgid,(void *)&sendmsg,MAX_TEXT,0)==-1)
  {
   perror("msgsnd");
   exit(1);
  }
  
  if(strncmp(buff,"end",3)==0)
  {
   printf("the program will exit\n");
   running=0;
  }
 }
 return 0;
}

 

接收端源代码

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <sys/msg.h>
#define MAX_TEXT 512

struct my_msg_rec
{
 int my_msg_type;
 char msg_text[MAX_TEXT];
};
typedef struct my_msg_rec  MSG_REC;

int main()
{
 int msgid;
 unsigned char running=1;
 char buff[MAX_TEXT];
 MSG_REC  recivemsg;
 printf("receive msg process is starting!\n");
 printf("the process id=%d\n",getpid());
 msgid=msgget((key_t)12345,0777|IPC_CREAT);
 if(msgid==-1)
 {
  perror("msgget");
  exit(1);
 }
 while(running)
 {
  memset(&recivemsg,0,sizeof(MSG_REC));
  //printf("please int msg:");
  //fgets(buff,MAX_TEXT,stdin);
  //recivemsg.my_msg_type =1;
  //strcpy(recivemsg.msg_text,buff);
  if(msgrcv(msgid,(void *)&recivemsg,MAX_TEXT,0,0)==-1)
  {
   perror("msgsnd");
   exit(1);
  }
  printf("the receive msg :%s",recivemsg.msg_text);
  
  if(strncmp(recivemsg.msg_text,"end",3)==0)
  {
   printf("the program will exit\n");
   running=0;
  }
 }
 return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值