linux 消息序列(进程间通信)

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>


//需要自己定义的消息队列结构
struct msgStuct
{
  long int msgType;
  char strMsg[1024];
};

int
main ()
{
  struct msgStuct msg_data;
  int msgid;
  char buffer[1024];
  //创建一个消息队列
  if ((msgid= msgget ((key_t) 2234, 0666 | IPC_CREAT)) == -1)
    {
      perror ("msgget failed with error: %d\n");
      exit (EXIT_FAILURE);
    }
  while (1)
    {
      printf ("Send message: ");
      fgets (buffer, 1024, stdin);
	//初始化消息类型
      msg_data.msgType = 1;
      strcpy (msg_data.strMsg, buffer);
	//发送消息
      if (msgsnd (msgid, (void *) &msg_data, 1024, 0) == -1)
	{
	  fprintf (stderr, "msgsnd failed\n");
	  exit (EXIT_FAILURE);
	}
      if (strncmp (buffer, "end", 3) == 0)
	{
	  break;
	}
    }
  exit (EXIT_SUCCESS);
}


#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

//需要自己定义的消息队列结构
struct msgStuct
{
  long int msgType;
  char strMsg[1024];
};

int
main ()
{
  int msgid;
  struct msgStuct msg_data;
  //接收消息优先级
  long int msgPriority = 0;//从队列中取第一个
  //创建一个消息队列
  if ((msgid= msgget ((key_t) 2234, 0666 | IPC_CREAT)) == -1)//类似open()创建一个文件返回它的文件描述符,这里是消息序列
    {
      perror ("msgget failed with error");
      exit (EXIT_FAILURE);
    }
  while (1)
    {
	//接收消息
      if (msgrcv (msgid, (void *) &msg_data, 1024,
		  msgPriority, 0) == -1)
	{
	  perror ("msgrcv failed with error");
	  exit (EXIT_FAILURE);
	}
      printf ("Received message: %s", msg_data.strMsg);
      if (strncmp (msg_data.strMsg, "end", 3) == 0)
	{
	  break;
	}
    }
  //删除消息队列
  if (msgctl (msgid, IPC_RMID, 0) == -1)
    {
      fprintf (stderr, "delete messagequeue error\n");
      exit (EXIT_FAILURE);
    }
  exit (EXIT_SUCCESS);
}

第一个是send.c,第二个是recieve.c

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值