/* * A simple program to illustrate the work of a pair of pipes * Textbook Figure 3.26 Page 144 */ #include #include #include #define BUFFER_SIZE 32 #define READ_END 0 // read 0 and write 1 can't be chosen randomly #define WRITE_END 1 int main(int argc, char * argv[]) { char sent_msg[BUFFER_SIZE] = "Greetings from child"; char read_msg[BUFFER_SIZE]; pid_t pid; int fd[2]; int amt_read; // number of bytes read char c; /* create the pipe */ if (pipe(fd) == -1) { fprintf(stderr," pipe failed \n"); return -1; } /* create a child process */ pid = fork(); if (pid < 0) { // error occured fprintf(stderr," fork failed \n"); return -2; } if (pid > 0) { // parent process /* close the pipe end not in use */ close(fd[READ_END]); char * c_msg = "===Hello from parent=="; /* write to the pipe */ write(fd[WRITE_END], c_msg, strlen(c_msg)); printf("In parent process, type a char to continue ...\n"); scanf("%c", &c); printf("In parent process, just wrote the message %s\n", sent_msg); printf("type a char to continue ...\n"); scanf("%c", &c); /* close the write end of the pipe */ close(fd[WRITE_END]); } else { // child process printf("In child process, waiting for message ...\n"); /* write to the pipe */ write(fd[WRITE_END], sent_msg, strlen(sent_msg)); /* read the messages from both the child and the parent itself */ amt_read = read(fd[READ_END], read_msg, BUFFER_SIZE); while (amt_read > 0) { read_msg[amt_read] = 0; // terminate the string printf("bytes read = %d\n", amt_read); printf("read -->%s<--\n", read_msg); amt_read = read(fd[READ_END], read_msg, BUFFER_SIZE); } /* close both ends of the pipe */ close(fd[READ_END]); close(fd[WRITE_END]); } return 0; }