1

我正在编写 ac 程序来实现多个管道,但由于 dup2 提前终止子进程而遇到了麻烦。这是我的代码:

// so you have i number of commands
fcommand = i;
for(i = 0; i < (fcommand - 1); ++i){
    if( pipe(fd + i*2) < 0 ){
        printf("Error!: cannot create file descripters\n");
        exit(5);
    }
}
++i;
printf("%d\n", i);
j = -1;
cdc = 0;
while(i >= 1){
    pid = fork();//creating a child
    if(pid == 0){//i.e. if its a child
        if(i != fcommand){//i.e. if there is a previous command
            if( dup2(fd[(cdc-1)*2], 0) < 0){// 0 -----> stdin
                printf("Error!: cannot duplicate file descriptors\n");
                exit(6);
            }
        }
        if(i != 1){
            if(dup2(fd[cdc*2+1], 1) < 0 ){// this is where the problem occurs
                printf("Error!: cannot duplicate file descriptors\n");
                exit(7);
            }
        }
        k = 0;
        while(k < ((2 * (fcommand - 1))))
            close(fd[k++]);
        ++j;
        if(execvp(in[j].enter[0], in[j].enter) < 0){
            printf("%s: command not found!\n", in[j].enter[0]);
            exit(1);
        }                               
    }
    else{ 
        if(pid < 0){//if error
            printf("Error!: cannot create a new process\n");
            exit(8);
        }
        if(pid > 0){//if a parent
            while(wait(&status) > 0);
            --i;
            cdc++;
        }
    }
}

当我运行命令时,我得到的输出是第一个命令的结果,然后程序终止而不执行管道中的其余命令。

dup2关于为什么会导致我的子进程过早终止的 任何想法?

4

0 回答 0