如何使用管道执行ls | wc-w?

如何使用管道执行ls | wc-w?,c,linux,terminal,pipe,wc,C,Linux,Terminal,Pipe,Wc,我试图创建一个shell程序来执行管道命令。当我从forked child调用ls,从parent调用wc时,效果很好。但若我也从分叉的孩子那个里打电话给wc,那个么父母会继续等待(我不知道为什么会发生这种情况) void execPiped(字符**Args,字符**pipedArgs) { int-pfds[2]; 管道(pfds); pid_t pid1=fork(); 如果(pid1==-1) { printf(“\n失败的分叉子项…”); 返回; } else if(pid1==0)/

我试图创建一个shell程序来执行管道命令。当我从forked child调用ls,从parent调用wc时,效果很好。但若我也从分叉的孩子那个里打电话给wc,那个么父母会继续等待(我不知道为什么会发生这种情况)

void execPiped(字符**Args,字符**pipedArgs)
{
int-pfds[2];
管道(pfds);
pid_t pid1=fork();
如果(pid1==-1)
{
printf(“\n失败的分叉子项…”);
返回;
}
else if(pid1==0)//正在执行子1
{
关闭(1);//关闭标准输出
dup(pfds[1]);//将pfds设置为标准输出
close(pfds[0]);//我们不需要这个
if(execvp(Args[0],Args)<0)
{
printf(“\n无法执行命令…”);
出口(1);
}
}
否则{
pid_t pid2=fork();
如果(pid2==-1)
{
printf(“\n失败的分叉子项…”);
返回;
}
else if(pid2==0)//正在执行子2
{
close(0);//关闭STDIN
dup(pfds[0]);//将pfds设置为标准
close(pfds[1]);//我们不需要这个
if(execvp(pipedArgs[0],pipedArgs)<0)
{
printf(“\n无法执行命令…”);
出口(1);
}
}
else{//Parent正在执行
//等待孩子们离开
等待(空);
等待(空);
}
返回;
}
}

您没有关闭子系统中足够的文件描述符。经验法则:如果将管道的一端连接到标准输入或标准输出,请尽快从
pipe()
关闭两个原始文件描述符。特别是,这意味着在使用任何函数族之前。该规则也适用于
dup()
F_DUPFD
。父进程还需要关闭管道的两端。否则,
wc
将永远不会获得EOF指示。请注意,错误消息应在标准错误上报告,而不是在标准输出上报告。另外,请阅读如何创建MCVE()。我们没有显示函数的调用上下文。您应该硬连线传递给函数的数据结构,但我们应该能够编译和运行程序,并看到您看到的问题-这意味着您需要描述预期和实际的输出(但在这种情况下,使用新创建的几乎为空的目录可能会有所帮助)。除此之外,请参阅。好的,我将尝试此方法
void execPiped(char** Args,char** pipedArgs)
{
    int pfds[2];
    pipe(pfds);
    pid_t pid1 = fork();
    if (pid1 == -1)
    {
        printf("\nFailed forking child..");
        return;
    }
    else if (pid1 == 0) //CHILD 1 EXECUTING
    {
        close(1);       //close STDOUT
        dup(pfds[1]);   //set pfds as STDOUT
        close(pfds[0]); //we don't need this
        if (execvp(Args[0], Args) < 0)
        {
            printf("\nCould not execute command..");
            exit(1);
        }
    }
    else {
        pid_t pid2 = fork();
        if (pid2 == -1)
        {
            printf("\nFailed forking child..");
            return;
        }
        else if (pid2 == 0) //CHILD 2 EXECUTING
        {
            close(0);       //close STDIN
            dup(pfds[0]);   //set pfds as STDIN
            close(pfds[1]); //we don't need this
            if (execvp(pipedArgs[0], pipedArgs) < 0)
            {
                printf("\nCould not execute command..");
                exit(1);
            }
        }
        else {  //Parent Executing
            //Wating for Children to exit
            wait(NULL);
            wait(NULL);
        }
        return;
    }
}