#include #include // Headers for wait #include #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; // The message to send to the child string message = "Hello from the parent!"; // Create a pipe to be used to talk to the child // Two sides of the pipe are created, a read side and a write side. The parent // program will send data to the child, and the child will display it to the // screen. int pipeFD[2]; if( pipe(pipeFD) == -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 pipe that we do not need close( pipeFD[READ_PIPE] ); // Send the message to the child write( pipeFD[WRITE_PIPE], message.c_str(), message.length() ); // Wait for the child to finish before exiting int status; pid = wait( &status ); // Close the remaining pipe close( pipeFD[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( pipeFD[WRITE_PIPE] ); // Read the message from the parent. We have to know how long the message // is going to be int length = message.length(); char longMessage[256]; read( pipeFD[READ_PIPE], longMessage, length ); // Display the message to the screen cout << "Child Process: Received Message..." << endl << longMessage << endl; // Close the remaining pipe close( pipeFD[READ_PIPE] ); } cout << "Terminating Process PID=" << getpid() << endl; return 0; }