0

I have a class that is handling reading/writing from a linux pipe. I currently have code in place that I can read data from the pipe and output it on the command line. Here is an example:

//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);
}

The above code reads my test message once, and then prints the output. Then it needs to be called again to read the next message. What I would like to be able to do is have something similar to the following:

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
  }
}

and then I want to (from the out of class function) have something similar to the following:

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);
}

Lastly, to make everything tricky, the system that I am building this for is an embedded system that doesn't support c++11.

Is there a way to do what I want here? Or am I stuck writing a loop that continuously calls the read function as my only way to check for when I get new information from the pipe?

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
user3830784
  • 355
  • 3
  • 17

0 Answers0