#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> void fun1() { pid_t fd; int pipefd[2]; if (0 > pipe(pipefd)) { fprintf(stderr, "pipe errno is %s\n", strerror(errno)); } else { } if (0 > (fd = fork())) { fprintf(stderr, "fork errno is %s\n", strerror(errno)); } else if (fd == 0) { //子进程 close(pipefd[0]); char buf[15] = { '\0' }; while (1) { fgets(buf, sizeof(buf) - 1, stdin); if (0 > write(pipefd[1], buf, sizeof(buf)-1)) { fprintf(stderr, "write errno is %s\n", strerror(errno)); } memset(buf, 0, sizeof(buf)); printf("chlid\n"); } close(pipefd[1]); exit(0); } else { //父进程 close(pipefd[1]); char buf[10] = { '\0' }; memset(buf, 0, sizeof(buf)); while (1) { int k=0; while (0!=(k= read(pipefd[0], buf, sizeof(buf) - 1))) { printf("parent = %s k=%d\n", buf,k); memset(buf, 0, sizeof(buf)); k=0; } // fprintf(stderr, "read errno is %s\n", strerror(errno)); } close(pipefd[0]); exit(0); } } int main(void) { fun1(); puts("!!!Hello World!!!"); /* prints !!!Hello World!!! */ return EXIT_SUCCESS; } |
|