C ++ - msgsnd& msgrcv似乎没有沟通

时间:2017-03-06 17:33:51

标签: c++

我正在尝试使用C ++进行两个进程通信,但是,它似乎不起作用。我有这段代码:

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>

void sender(int qid)
{
  // declare my message buffer
  struct buf {
    long mtype; // required
    char greeting[50]; // mesg content
  };

  buf msg;
  int size = sizeof(msg)-sizeof(long);

  std::cout << "Type [exit] to stop the program." << std::endl;

  bool exit = false;
  while (!exit)
    {
      std::cout << getpid() << ": ";
      std::cin.getline(msg.greeting, 50, '\n');
      //std::cout << msg.greeting << std::endl;
      msg.mtype = 23;
      if (strcmp(msg.greeting, "exit") == 0)
    exit = true;
      msgsnd(qid, (struct msgbuf *)&msg, size, 0);
    }

}

void receiver(int qid)
{
  // declare my message buffer
  struct buf {
    long mtype;
    char greeting[50];
  };
  buf msg;
  int size = sizeof(msg)-sizeof(long);

  bool exit = false;
  while (!exit)
    {
      msgrcv(qid, (struct msgbuf *)&msg, size, 23, 0);
      if (strcmp(msg.greeting, "exit") == 0)
    exit = true;
      std::cout << getpid() << ": " << msg.greeting << std::endl;
    }
}

int main(int ac, char **av) {

  //spawning two child processes
  pid_t cpid = fork();
  int qid = msgget(IPC_PRIVATE, IPC_EXCL|IPC_CREAT|0600);

  if (cpid == 0) {
    //    execv("./sender", av);
    sender(qid);
    exit(0);
  }
  cpid = fork();
  if (cpid == 0) {
    //execv("./receiver", av);
    receiver(qid);
    exit(0);
  }

  while (wait(NULL) != -1); // waiting for both children to terminate

  msgctl(qid, IPC_RMID, NULL);

  std::cout << "END" << std::endl;

  exit(0);
}

正如您所看到的,sender()等待用户的输入。 receiver()正等待,所以一切都好。但是,当用户完成输入后,他按[enter]但是......接收器没有得到任何东西。

它们具有相同的QID,相同大小的msg,相同的ID(23)..我不知道为什么它不起作用。我看到很多例子,对我来说,似乎逻辑如此,问题是什么?

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

此代码中的一个错误是每个进程都创建自己的专用IPC队列。

让他们共享同一个队列,以便能够通过它进行通信:

//spawning two child processes
int qid = msgget(IPC_PRIVATE, IPC_EXCL|IPC_CREAT|0600);
pid_t cpid = fork();