/* The parent will send messages to the child that * will be read 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 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; } 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] ); // 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() ); cout << "Parent Process: Sending message: " << message << endl; // Send the message to the child write( pipeParentFD[WRITE_PIPE], message, input.length() + 2 ); } // Wait for the child to finish before exiting int status; pid = wait( &status ); // Close the remaining pipe close( pipeParentFD[WRITE_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] ); 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: Read message: " << output << endl; if( output == "exit" ) { break; } } // Close the remaining pipe close( pipeParentFD[READ_PIPE] ); } cout << "Terminating Process PID=" << getpid() << endl; return 0; }