/* Open two pipes in this example. This allows for bi-directional * communication. The parent will send messages to the child that * are to be put into uppercase. The parent will read the messages * from the keyboard. * * MESSAGE FORMAT: First two bytes show the length of the message to read. * The message will follow the first two bytes */ #include #include #include // Headers for wait #include #include // Header needed for atoi function #include // Header needed for toupper function #include using namespace std; #define READ_PIPE 0 #define WRITE_PIPE 1 int main( int argc, char * argv[] ) { cout << "Original Process: PID=" << getpid() << " PPID=" << getppid() << endl; // Create a pipe to be used to talk to the child int pipeParentFD[2]; if( pipe(pipeParentFD) == -1 ) { cout << "Error, cannot create pipe" << endl; return 0; } // Create the pipe that will allow the child to talk to the parent int pipeChildFD[2]; if( pipe(pipeChildFD) == -1 ) { cout << "Error, cannot create pipe" << endl; return 0; } int pid = fork(); if( pid != 0 ) { // This is the parent process cout << "Parent Process: PID=" << getpid() << " PPID=" << getppid() << endl; // We must close the side of the pipes that we do not need close( pipeParentFD[READ_PIPE] ); close( pipeChildFD[WRITE_PIPE] ); // Read a line from the keyboard and send it to the child string input; while( input != "exit" ) { getline( cin, input ); char message[100]; sprintf( message, "%02d%s", input.length(), input.c_str() ); // Send the message to the child write( pipeParentFD[WRITE_PIPE], message, input.length() + 2 ); // Read the incoming message from the child. We know how long the // message is supposed to be already read( pipeChildFD[READ_PIPE], message, input.length() ); message[input.length()] = '\0'; cout << "Parent Process: Received Message: " << message << endl; } // Wait for the child to finish before exiting int status; pid = wait( &status ); // Close the remaining pipe close( pipeParentFD[WRITE_PIPE] ); close( pipeChildFD[READ_PIPE] ); } else { // This is the child process cout << "Child Process: PID=" << getpid() << " PPID=" << getppid() << endl; // We must close the side of the pipe that we do not need close( pipeParentFD[WRITE_PIPE] ); close( pipeChildFD[READ_PIPE] ); while( true ) { // Read the first two bytes. These two bytes tell us how long // the message is going to be char length[3] = " "; read( pipeParentFD[READ_PIPE], length, 2 ); int messageLength = atoi(length); // Read the rest of the message char longMessage[256]; read( pipeParentFD[READ_PIPE], longMessage, messageLength ); longMessage[messageLength] = '\0'; string output = longMessage; cout << "Child Process: Received message: " << output << endl; // Uppercase the entire message for( int i=0; i