Linux消息队列编程

文件msg为空文件,可以为任何内容,这里只是为了ftok函数使用。程序通过建立消息队列,完成进程间通信,注意msgrcv的第四个参数为消息类型,他定义了从队列中取消息的类型。

下面是msgLucy.c,是建立消息队列的

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

#include<stdio.h>
#include<fcntl.h>
#include<signal.h>
#include<stdlib.h>
#include<string.h>

#define PROJID 0xFF
#define LUCY 1
#define PETER 2

int mqid;

void terminate_handler(int signo)
{
 msgctl(mqid,IPC_RMID,NULL);
 exit(0);
}

int main()
{
 char filenm[] = "msg";
 key_t mqkey;
 struct msgbuf
 {
      long mtype;      /* message type, must be > 0 */
    char mtext[256];  /* message data */
   }msg;
 int ret;

 mqkey = ftok(filenm,PROJID);
 if(mqkey == -1)
 {
  perror("ftok error: ");
  exit(-1);
 }

 mqid = msgget(mqkey,IPC_CREAT | IPC_EXCL | 0666);
 if(mqid == -1)
 {
  perror("msgget error: ");
  exit(-1);
 }

 signal(SIGINT, terminate_handler);
 signal(SIGTERM, terminate_handler);

 while(1)
 {
  printf("Lucy: ");
  fgets(msg.mtext, 256, stdin);
  if (strncmp("quit", msg.mtext, 4) == 0)
  {
   msgctl(mqid,IPC_RMID,NULL);
   exit(0);
  }
  msg.mtext[strlen(msg.mtext)-1] = '/0';
  msg.mtype = LUCY;
  msgsnd(mqid,&msg,strlen(msg.mtext) + 1,0);
  msgrcv(mqid,&msg,256,PETER,0);
  printf("Peter: %s/n", msg.mtext);  
 }  
}

下面的是msgPeter,是和Lucy通信的,程序先运行Lucy,再运行Peter

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

#include<stdio.h>
#include<fcntl.h>
#include<signal.h>
#include<string.h>
#include<stdlib.h>

#define PROJID 0xFF
#define LUCY 1
#define PETER 2

int main()
{
 char filenm[] = "msg";
 int mqid;
 key_t mqkey;
 struct msgbuf
 {
         long mtype;      /* message type, must be > 0 */
         char mtext[256];  /* message data */
   }msg;
 int ret;

 mqkey = ftok(filenm, PROJID);
 if(mqkey == -1)
 {
  perror("ftok error: ");
  exit(-1);
 }

 mqid = msgget(mqkey, 0);
 if(mqid == -1)
 {
  perror("msgget error: ");
  exit(-1);
 }

 while(1)
 {
  msgrcv(mqid,&msg,256,LUCY,0);
  printf("Lucy: %s/n",msg.mtext);
  printf("Peter: ");
  fgets(msg.mtext,256,stdin);
  if(strncmp("quit", msg.mtext, 4) == 0)
  {
   exit(0);
  }
  msg.mtext[strlen(msg.mtext)-1] = '/0';
  msg.mtype = PETER;
  msgsnd(mqid,&msg,strlen(msg.mtext) + 1,0);
 } 
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值