在c++中从一个程序打开两个管道

Opening 2 pipes in c++ from 1 program

本文关键字:两个 管道 程序 一个 c++      更新时间:2023-10-16

我有一个程序,我正在为嵌入式设备编写,我正试图使用管道传递消息。在我的程序和另一个程序之间传递消息之前,我正在构建测试代码,以确保一切正常工作,然后遇到了一个问题。请注意,嵌入式设备不支持c++11(因此使用pthread’s)。

所讨论的代码:

void* testSender(void *ptr) {
  std::cout << "Beginning testSender" << std::endl;
  int pipe = open("/dev/rtp10", O_WRONLY);
  if (pipe < 0) {
    std::cout << "write pipe failed to open" << std::endl;
  } else {
    std::cout << "write pipe successfully opened" << std::endl;
  }
  std::cout << "Ending testSender" << std::endl;
  return NULL;
}
void* testReceiver(void *ptr) {
  std::cout << "Beginning testReceiver" << std::endl;
  int pipe = open("/dev/rtp10", O_RDONLY);
  if (pipe < 0) {
    std::cout << "read pipe failed to open" << std::endl;
  } else {
    std::cout << "read pipe successfully opened" << std::endl;
  }
  std::cout << "Ending testReceiver" << std::endl;
  return NULL;
}
void testOpenClosePipes() {
  std::cout << "Beginning send/receive test" << std::endl;
  pthread_t sendThread, receiveThread;
  pthread_create(&sendThread, NULL, &testSender, NULL);
  pthread_create(&receiveThread, NULL, &testReceiver, NULL);
  std::cout << "waiting for send and receive test" << std::endl;
  pthread_join(receiveThread, NULL);
  pthread_join(sendThread, NULL);
  std::cout << "Done testing open send/receive" << std::endl;
}

函数teststopenclosepipes()从我的主线程调用,调用它后,我得到以下输出:

Beginning send/receive test
waiting for send and receive test
Beginning testReceiver
Beginning testSender
write pipe failed to open
Ending testSender

,然后程序挂起。我相信这是因为读管道已经打开,然后等待发送方连接到管道,但我可能错了。注意,如果我在启动发送线程之前启动接收线程,那么结果如下:

Beginning send/receive test
waiting for send and receive test
Beginning testSender
Beginning testReceiver
read pipe failed to open
Ending testReceiver

从我迄今为止读到的关于管道的内容来看,似乎正在发生的事情是两个(发送或接收)中的一个正确打开,然后保持直到管道的另一端打开。然而,管道的另一端无法正确打开,这最终导致系统挂起,因为打开的管道在成功移动之前等待其连接。我无法弄清楚为什么会发生这种情况,但是,我希望得到帮助,

在审查我的问题之后,似乎问题实际上并不在于所讨论的管道的使用,而是/dev/rtp*为嵌入式系统的特殊应用打开了一个管道,而实际上并不是一个可以从linux到linux的管道。这个问题可以通过使用不同的管道来解决,并在尝试打开管道之前先使用mkfifo命令创建该管道。

如何检查公开呼叫失败的errno值?