#include #include #include #include #include using namespace std; int main () { /* Pipes are similar to files, and establish uni-directional communication. Each pipe has two file descriptors, one for read (0) and the other for write (1) operation. Here we create two pipes, to establish bidirectional communication. For uni-directional communication, only one pipe is sufficient. To compile: g++ unnamed-pipe.cpp -o unnamed-pipe */ int parent2child[2], child2parent[2]; pid_t childpid; pipe(parent2child); pipe(child2parent); childpid = fork(); if(childpid == 0) { char readbuffer[80]; char str1[] = "Hello Parent! \n"; /* Child process closes up the ones used by the parent */ close(child2parent[0]); close(parent2child[1]); /* Send a string through the output side of pipe */ write(child2parent[1], str1 , (strlen(str1)+1)); cout << "Child sent " << str1 << endl; /* Read in a string from the pipe */ read(parent2child[0], readbuffer, sizeof(readbuffer)); cout << "Child received "<< readbuffer << endl;; } else { char readbuffer[80]; stringstream ss; ss << "Hello child #" << childpid << "!"; char* str2 = (char*) ss.str().c_str(); /* Parent process closes up the ones used by the child */ close(child2parent[1]); close(parent2child[0]); /* Read in a string from the pipe */ read(child2parent[0], readbuffer, sizeof(readbuffer)); cout << "Parent received "<< readbuffer << endl;; /* Send a string through the output side of pipe */ write(parent2child[1], str2 , (strlen(str2)+1)); cout << "Parent sent " << str2 << endl; } return 0; }