Linux高级编程基础——进程间通信之用一个消息队列实现多个进程的通信

进程间通信之用一个消息队列实现多个进程的通信

  1. 进程a向进程B发送hello world,进程B接收打印,

  2. 进程c向进程d发送自己的学号班级姓名,进程d接收打印,

  3. 用同一个消息队列实现

                      这是a进程
    
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

struct msg{
  long msg_types;
  char msg_buf[512];
};

int main()
{
   key_t key;
   key = ftok (".",5);
   int msgdis;
   if ((msgdis = msgget (key,IPC_CREAT|777)) == -1) { perror("msgget : \n"); exit(1); }
     printf ("消息队列为:%d \n",msgdis);
   struct msg pmsg;
   pid_t pid;
   pid = getpid();
   pmsg.msg_types = pid;
   printf ("设置的消息类型为: %d \n",pid);
   sprintf (pmsg.msg_buf,"%s","hello world");
   int len;
   len = strlen (pmsg.msg_buf);
   if ((msgsnd(msgdis,&pmsg,len,0)) == -1)  { perror("msgsnd"); exit(1);}
   
return 0;
}
             这是 b 进程
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define BUFSIZE 4096

struct msg{
  long msg_types;
  char msg_buf[512];
};

int main()
{
 int pid,mpid;
   printf ("你想要在那个消息队列中读取消息 \n");
   scanf ("%d",&mpid);
   printf ("你想要读取的消息类型 \n");
   scanf ("%d",&pid);

   struct msg pmsg;
 int len;
   if ( (len = msgrcv(mpid,&pmsg,BUFSIZE,pid,0)) == -1)   { perror ("msgrcv : "); exit (1); }
   pmsg.msg_buf[len] = '\0';
   printf ("message text : %s \n",pmsg.msg_buf);
return 0;
}


            这是  c  进程
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

struct msg{
  long msg_types;
  char msg_buf[512];
};

int main()
{
   
   int msgdis;
   printf ("请输入你所在的消息队列为:\n");
   scanf ("%d",&msgdis);
   struct msg pmsg;
   pid_t pid;
   pid = getpid();
   pmsg.msg_types = pid;
   printf ("设置的消息类型为: %d \n",pid);
   sprintf (pmsg.msg_buf,"%s","学号:1715925506 班级:移动三班 姓名:彭振生");
   int len;
   len = strlen (pmsg.msg_buf);
   if ((msgsnd(msgdis,&pmsg,len,0)) == -1)  { perror("msgsnd"); exit(1);}
   
return 0;
}

               这是  d  进程
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define BUFSIZE 4096

struct msg{
  long msg_types;
  char msg_buf[512];
};

int main()
{
 int pid,mpid;
   printf ("你想要在那个消息队列中读取消息 \n");
   scanf ("%d",&mpid);
   printf ("你想要读取的消息类型 \n");
   scanf ("%d",&pid);

   struct msg pmsg;
 int len;
   if ( (len = msgrcv(mpid,&pmsg,BUFSIZE,pid,0)) == -1)   { perror ("msgrcv : "); exit (1); }
   pmsg.msg_buf[len] = '\0';
   printf ("message text : %s \n",pmsg.msg_buf);
return 0;
}



``

**如果有任何不懂的可以留言,我看到会给解答的**



你可能感兴趣的:(Linux)