if (pid == 0) { /* this is child. */ printf("Child pid is: %d\n", getpid()); if (read(pipefd[0], buf, BUFSIZ) < 0) { //子进程读管道中父进程写入的信息 perror("write()"); //没有读到的话就是写出现了问题 exit(1); }
printf("%s\n", buf); //将从父进程得到的信息打印
bzero(buf, BUFSIZ); //将buf清零 //将要送给parent的信息写入buf中 snprintf(buf, BUFSIZ, "Message from child: My pid is: %d", getpid()); //调用pipe()的写入实现 if (write(pipefd[1], buf, strlen(buf)) < 0) { perror("write()"); exit(1); }
} else { /* this is parent */ printf("Parent pid is: %d\n", getpid()); //将要送给子进程的信息写入buf snprintf(buf, BUFSIZ, "Message from parent: My pid is: %d", getpid()); //调用pipe()的写入实现 if (write(pipefd[1], buf, strlen(buf)) < 0) { perror("write()"); exit(1); }