//Program for half-duplex communication #include <iostream> using namespace std; #include<stdlib.h> #include <stdio.

h> #include <unistd.h> int main() { int status, pid, pipefds[2],ch,i; char instring[20]; for(i=0;i<20;i++) instring[i]='\0'; cout<<"-------------Program for half duplex communication-------------\n"; cout<<"-------------Press 1 for child to parent communication\n"; cout<<"-------------Press 2 for parent to child communication\n"; scanf("%d",&ch); /* Create the pipe and return 2 file descriptors in the pipefds array */ /* This operation is done before the fork so that both processes will */ /* know about the same pipe, which will allow them to communicate. */ status = pipe(pipefds); if (status == -1) { perror("Trouble"); exit(1); } /* create child process; both processes continue from here */ pid = fork(); if (pid == -1) { perror("Trouble"); exit(2); } switch(ch) { case 1: // child to parent communication if (pid == 0) /* child : sends message to parent*/ { /* close unused end of pipe */ /* because this process only needs to write */ close(pipefds[0]); /* send 7 characters in the string, including end-of-string */ cout << "About to send a message: " << endl; write(pipefds[1], "Hi father!", 10);

7). } /* parent : receives message from child */ . default: cout<<"This is a problem". exit(0). close(pipefds[1]). exit(0). close(pipefds[0]). /* read from the pipe */ read(pipefds[0]. write(pipefds[1]. } break. 7). instring. "Hi son!". exit(0). } else { /* close unused end of pipe */ /* because this process only needs to read */ close(pipefds[1]). exit(0). cout << "Just received a message that says: " << instring << endl. /* send 7 characters in the string.close(pipefds[1]). close(pipefds[0]). } else { /* close unused end of pipe */ /* because this process only needs to read */ close(pipefds[1]). instring. including end-of-string */ cout << "About to send a message: " << endl. /* read from the pipe */ read(pipefds[0]. case 2: // parent to child communication if (pid > 0) { /* close unused end of pipe */ /* because this process only needs to write */ close(pipefds[0]). 10). cout << "Just received a message that says: " << instring << endl. } break.

} .return 0.