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

时间:2018-09-03 15:58:55

标签: c linux terminal pipe wc

我正在尝试创建一个Shell程序来执行管道命令。当我从分叉的孩子打电话给ls和从父母打来的wc时,它工作正常。但是如果我也从分叉的孩子那里打电话给wc,父母就会继续等待(我不知道为什么会这样)。

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;
    }
}

0 个答案:

没有答案