[求助]fork与pipe
最近在学操作系统,用到了linux,编程用到了fork和pipe,实现 ls -l | more 的功能。代码中最后的两个close如果不写,程序就不终止,这是为什么呢?谢谢各位。
#include <stdio.h>#include <unistd.h>#include <sys/wait.h>int main(){ pid_t pid[3]; int pipe_fd[2]; int status; char *prog1[3] = {"/bin/ls", "-l", NULL}; char *prog2[2] = {"/bin/more", NULL}; if(pipe(pipe_fd) < 0){ perror("pipe 1 failed"); } if((pid[0] = fork()) < 0){ perror("fork find failed"); } if(pid[0] == 0){ close(pipe_fd[0]); dup2(pipe_fd[1], 1); close(pipe_fd[1]); execvp(prog1[0], prog1); } if(pid[0] > 0){ pid[1] = fork(); if(pid[1] == 0){ close(pipe_fd[1]); dup2(pipe_fd[0], 0); close(pipe_fd[0]); execvp(prog2[0], prog2); } close(pipe_fd[0]); close(pipe_fd[1]); waitpid(pid[1], &status, 0); } return 0;}