用管道分叉

时间:2010-04-08 00:27:19

标签: c process pipe unix

我试过在main中做fork()和管道,它工作得很好但是当我尝试在某个函数中实现它时由于某种原因我没有得到任何输出,这是我的代码:

void cmd(int **pipefd,int count,int type, int last);    

int main(int argc, char *argv[]) {
int pipefd[3][2];
int i, total_cmds = 3,count = 0;
int in = 1;

for(i = 0; i < total_cmds;i++){
 pipe(pipefd[count++]);
 cmd(pipefd,count,i,0);    
}

 /*Last Command*/
 cmd(pipefd,count,i,1);    

exit(EXIT_SUCCESS);
}

void cmd(int **pipefd,int count,int type, int last){    
    int child_pid,i,i2;

     if ((child_pid = fork()) == 0) {

            if(count == 1){
               dup2(pipefd[count-1][1],1); /*first command*/
            }
            else if(last!=1){
               dup2(pipefd[count - 2][0],0); /*middle commands*/
               dup2(pipefd[count - 1][1],1);
            }
            else if(last == 1){
               dup2(pipefd[count - 1][0],0); /*last command*/
            }


            for(i = 0; i < count;i++){/*close pipes*/
            for(i2 = 0; i2 < 2;i2++){
               close(pipefd[i][i2]);
            }}



            if(type == 0){
                execlp("ls","ls","-al",NULL);
            }
            else if(type == 1){
                execlp("grep","grep",".bak",NULL);
            }
            else if(type==2){
                               execl("/usr/bin/wc","wc",NULL);
            }
            else if(type ==3){
                         execl("/usr/bin/wc","wc","-l",NULL);
           }
            perror("exec");
            exit(EXIT_FAILURE);
    }
    else if (child_pid < 0) {
            perror("fork");
            exit(EXIT_FAILURE);
    }
}

我检查了文件描述符,它正在打开正确的文件描述符,不确定是什么问题 可能是..

编辑:我修复了问题,但是我有子进程,哪种方式最好等待子进程,而(wait(NULL)!= - 1);但那挂了

1 个答案:

答案 0 :(得分:2)

问题是pipefd不是int**,而是int[3][2],因此当您将其传递给cmd时,您会遇到垃圾。您的编译器在每次调用cmd()时向您发出警告,例如:

warning: passing argument 1 of 'cmd' from incompatible pointer type

如果没有,请调高警告级别。

确实,数组会衰减成指向其第一个元素的指针,因此您可以将1-D数组传递给期望指针的函数,但仅对数组的第一维维度。特别是,2D数组衰减成指向指针的指针。它仅在第一级衰减,因此pipefd可以衰减为int (*)[2]类型,该类型被读作“指向int的数组2的指针”

因此,写cmd的正确方法是:

void cmd(int (*pipefd)[2],int count,int type, int last)
相关问题