首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 操作系统 > UNIXLINUX >

[]fork与pipe

2012-03-23 
[求助]fork与pipe最近在学操作系统,用到了linux,编程用到了fork和pipe,实现 ls -l | more 的功能。代码中最

[求助]fork与pipe
最近在学操作系统,用到了linux,编程用到了fork和pipe,实现 ls -l | more 的功能。代码中最后的两个close如果不写,程序就不终止,这是为什么呢?谢谢各位。

C/C++ code
#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;}


[解决办法]
关闭管道是为了结束more命令的输入
否则,more不会终止,它一直在尝试读取管道
[解决办法]
dup2(pipe_fd[1], 1);
close(pipe_fd[1]);


楼主完全不懂dup2是干什么的, 刚dup2完又关掉了, 你让子进程标准输出到哪.
[解决办法]
探讨
dup2(pipe_fd[1], 1);
close(pipe_fd[1]);


楼主完全不懂dup2是干什么的, 刚dup2完又关掉了, 你让子进程标准输出到哪.

[解决办法]
探讨
引用:
dup2(pipe_fd[1], 1);
close(pipe_fd[1]);


楼主完全不懂dup2是干什么的, 刚dup2完又关掉了, 你让子进程标准输出到哪.


不好意思,看错了,是close(pipe_fd[1]),sorry。。。 1#说的是正确的

热点排行