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

本次进程间通信使用了消息队列,编写了两个程序,一个用于发送消息,一个用于读取消息.

发送消息msgWrite.c如下:

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

void *pAddr;
int msgId;

struct MSG{//msgsnd要填入的消息参数格式
  long mtype; 
  char content[36];
};

struct Student{
  int id;
  char name[32];
};

void Handle(int s){
  if(s == 2)
  {
     msgctl(msgId,IPC_RMID,0);
     exit(0);
  }
} 

int main(){
  signal(2,Handle);//ctrl+c键退出程序时删除消息队列

  key_t key = ftok(".",4);
  msgId = msgget(key,IPC_CREAT | IPC_EXCL | 0666);

  if(msgId == -1){
    printf("shmat error!\n"); 
    exit(0);
  }
  
  int stuid = 0;
  struct Student stu;
  struct MSG msg;
  while(1){ 
    stuid++;
    stu.id = stuid; 
    printf("input name:");
    scanf("%s",stu.name);

    msg.mtype = 2;
    memcpy(msg.content,&stu,sizeof(stu));
    msgsnd(msgId,&msg,sizeof(msg),0); 
  }
  return 0;
}

读消息msgRead.c如下:

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

void *pAddr;
int msgId;

struct MSG{
  long mtype; 
  char content[36];
};

struct Student{
  int id;
  char name[32];
};


int main(){
  key_t key = ftok(".",4);
  msgId = msgget(key,0);


  if(msgId == -1){
    printf("shmat error!\n"); 
    exit(0);
  }
  struct MSG msg;
  while(1){ 
    if(msgrcv(msgId,&msg,sizeof(msg),2,0) == -1)//若发送消息程序已退出,则本程序也退出
    {
      exit(0);
    }
    else{
      struct Student *stu = (struct Student *)msg.content;
      printf("%d : %s\n",stu->id,stu->name);
    }
  }
  return 0;
}

运行结果如下:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值