C++ dup2()提前终止子进程

C++ dup2()提前终止子进程,c++,c,process,pipe,dup2,C++,C,Process,Pipe,Dup2,我正在编写一个c程序来实现多个管道,但由于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);

我正在编写一个c程序来实现多个管道,但由于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++;
        }
    }
}
//所以您有很多命令
fcommand=i;
对于(i=0;i<(fcommand-1);+i){
如果(管道(fd+i*2)<0){
printf(“错误!:无法创建文件描述符\n”);
出口(5);
}
}
++一,;
printf(“%d\n”,i);
j=-1;
cdc=0;
而(i>=1){
pid=fork();//创建子对象
如果(pid==0){//,即如果它是一个子
如果(i!=fcommand){//,即如果有先前的命令
如果(dup2(fd[(cdc-1)*2],0)<0){//0----->stdin
printf(“错误!:无法复制文件描述符\n”);
出口(6);
}
}
如果(i!=1){
如果(dup2(fd[cdc*2+1],1)<0){//这就是问题发生的地方
printf(“错误!:无法复制文件描述符\n”);
出口(7);
}
}
k=0;
而(k<((2*(fcommand-1)))
关闭(fd[k++]);
++j;
if(execvp(在[j]中输入[0],在[j]中输入)<0){
printf(“%s:未找到命令!\n”,在[j]中。输入[0]);
出口(1);
}                               
}
否则{
if(pid<0){//if错误
printf(“错误!:无法创建新进程\n”);
出口(8);
}
如果(pid>0){//如果是父级
while(等待和状态)>0;
--一,;
cdc++;
}
}
}
当我运行命令时,我得到的输出是第一个命令的结果,然后程序终止,而不执行管道中的其余命令


关于为什么
dup2
会导致我的子进程提前终止,有什么想法吗

dup2(fd[(cdc-1)*2],
它出现在
cdc
从零开始,因此cdc-1将为负。但是它不会第一次出现在那里,因为我有条件“如果不是第一个命令”。cdc-1在
i!=fcommand
子句中引用,而不是在
i!=1
子句中引用。您的索引是fubar。