#include #include #include #include #include #define MAXLINE 256 /** * This program sets up a pipe, forks a child, and closes the appropriate * descriptors for a one-way pipe from the parent to the child. * The parent then sends a string down the pipe, which the child reads * from the pipe and then prints to stdout. */ int main() { pid_t pid; int n; char line[MAXLINE]; int pipefd[2]; if (pipe(pipefd) < 0)/* Create a pipe. */ { fprintf(stderr, "Pipe error!\n"); exit(-1); } pid = fork(); /* fork another process */ if (pid < 0) /* Forking error! */ { exit(-1); } else if (0 == pid) /* Child process */ { close(pipefd[1]); /* Child closes write end of pipe. */ // It doesn't matter if the child gets to the read() function // before the parent has called write(); the child will // wait here until there is something to read from the pipe. n = read(pipefd[0], line, MAXLINE); if (n > 0) printf("Child got %s\n", line); close(pipefd[0]); /* Done with pipe. */ exit(0); } else /* pid > 0: Parent process */ { close(pipefd[0]); /* Parent closes read end of pipe. */ // Parent sends a string down the pipe to the child. write(pipefd[1], "Hello World!", 12); wait(NULL); close(pipefd[1]); /* Done with pipe. */ exit(0); } }