【问题标题】:Forking with Pipes用管道分叉
【发布时间】:2010-04-08 00:27:18
【问题描述】:

我尝试在 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);
    }
}

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

编辑:我解决了问题,但我有子进程,哪种方式最好等待子进程,while(wait(NULL)!=-1);但这挂了

【问题讨论】:

标签: c process pipe unix


【解决方案1】:

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

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

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

数组确实会衰减为指向其第一个元素的指针,因此您可以将一维数组传递给需要指针的函数,但仅适用于数组的第一个维度。特别是,二维数组不会衰减为指向指针的指针。它只在第一级衰减,所以pipefd可以衰减为int (*)[2]类型,读作“指向int的数组2的指针”

那么,cmd 的正确写法是这样的:

void cmd(int (*pipefd)[2],int count,int type, int last)

【讨论】:

  • Ahh Okay 这解决了一些问题,但这种方法将是杀死子进程的最佳方法
猜你喜欢
  • 1970-01-01
  • 2013-11-10
  • 1970-01-01
  • 2010-12-14
  • 2016-03-13
  • 1970-01-01
  • 1970-01-01
  • 2013-11-18
  • 2015-04-30
相关资源
最近更新 更多