LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 780|回复: 1

[C] 关于IO重定向的问题

[复制链接]
发表于 2009-2-16 18:00:33 | 显示全部楼层 |阅读模式
我要写一个程序,产生2个进程,进程2接管进程1的IO

下面是我的程序,一直不成功,不知道什么原因,请高手解答

以下这个编译成cal
#include <stdio.h>

int main(){
    int a,b;
    for( ;; ){
        scanf("%d%d", &a, &b);
        printf("%d\n", a+b);
    }   

    return 0;
}



以下这个程序做IO接管的工作,不知道问题出在哪了
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/ptrace.h>
#include <sys/reg.h>
#include <unistd.h>

int main(){

    pid_t pid;

    int pipe_fdr[2];
    int pipe_fdw[2];
   
    if( pipe(pipe_fdr) == -1 ){
        perror("pipe failed!\n");
        exit(0);
    }

    if( pipe(pipe_fdw) == -1 ){
        perror("fork failed!\n");
        exit(0);
    }

    pid = fork();

    if( pid == 0 ){

        if( dup2(pipe_fdr[0], 0) == -1 ){
            perror("dup failed!\n");
            exit(0);
        }

        if( dup2(pipe_fdw[1], 1) == -1 ){
            perror("dup failed!\n");
            exit(0);
        }

        if(execl("./cal", "cal", NULL) <0 ){
            printf("Error!!\n");
        }

    }else{
        while(1){
            wait(NULL);
            FILE* in = fdopen(pipe_fdr[1], "w");
            FILE* out = fdopen(pipe_fdw[0], "r");
            char line[4096];
            fgets(line, 4096, stdin);
            fprintf(in, line);
            fgets(line, 4096, out);
            printf(line);
        }
    }

    return 0;
}
发表于 2009-2-21 12:32:31 | 显示全部楼层
帮你顶一下吧
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表