如何创建一个从管道重复读取的类函数?

时间:2016-10-28 17:23:11

标签: c++ linux

我有一个处理从linux管道读/写的类。我目前有代码,我可以从管道读取数据并在命令行输出。这是一个例子:

//readPipeFD is the file handler declared and opened elsewhere
//currently testing with sending the string "Hello #"
//with # = to the number of times it is sent
void MyPipe::readFromPipe(){
  char data[256];
  ssize_t bytesReceived = read(readPipeFD, data, 256);
  if (0 > bytesReceived) {
    //error handling
    return;
  }
  data[bytesReceived] = 0;
  printf("Receieved message: %s\n", data);
}

上面的代码读取我的测试消息一次,然后打印输出。然后需要再次调用它来读取下一条消息。我希望能够做的事情与以下内容类似:

void MyPipe::readFromPipe(){
  ssize_t bytesReceived;
  char data[256];
  while (true) { //put in an exit clause later
    bytesReceived = read(readPipeFD, data, 256);
    //forward bytesReceived and data on to an out of class function
    //that then handles what to do with the data
  }
}

然后我想(来自课外功能)有类似以下内容:

MyPipe connection;
myConnectedReader(){
  //gets called whenever new data is received from
  //MyPipe::readFromPipe()
  //does something with data: ex.
  printf("Receieved message: %s\n", data);
}

int main(){
  connection.openReadPipe();
  //connect myConnectedReader in another thread
  pthread_t myReader;
  pthread_create(&myReader, NULL, &myConnectedReader, NULL); 

  while (true){ //exit condition to be determined later
    sleep(1);
  }
  pthread_join(myReader, NULL);
}

最后,为了使一切变得棘手,我构建的系统是一个不支持c ++ 11的嵌入式系统。

有没有办法在这里做我想做的事情?或者我是不是写了一个循环,不断调用读取函数作为我从管道获取新信息时检查的唯一方法?

0 个答案:

没有答案