如何使用管道运行命令? [英] How to run a command using pipe?

查看:318
本文介绍了如何使用管道运行命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图运行ls |厕所使用execvp。所以我创建了一个管道,然后叉创建一个子。我关闭父/子合适(read./write)结束,然后映射另一端连接到标准输出/标准输入。然后我用运行和execvp厕所在孩子父母的LS。当我运行程序它说

I am trying to run ls|wc using execvp. So I create a pipe and then fork to create a child. I close the appropriate(read./write) end in parent/child and then map the other end to stdout/stdin. Then I run the ls in parent using execvp and wc in child. When I run the program it says

 wc:standard input:bad file descriptor.
 0 0 0
 wc: -:Bad file descriptor

下面是我的code:

int main()
{
//int nbBytes = 0; //stream length
int pfd_1[2]; //file descriptor 
//char buffer[MAX_FILE_LENGTH]; 
char* arg[MAX_FILE_LENGTH];
pid_t processPid;

//Create a pipe

if(pipe(pfd_1) == -1)
{
    printf("Error in creating pipe");
    return 0;
}

//Create a child
processPid = fork();

if(processPid == -1)
{
    printf("Erro in fork");
    exit(1);
}   
else if(processPid == 0) //Child
{               
    //redirect read end file descriptor to standard input
    dup2(pfd_1[0],0);
    //Close the write end
    if(close(pfd_1[1] == -1))
    {
        printf("Error in closing the write end file descriptor");
        exit(1);
    }
    arg[0] = "wc";
    //arg[1] = "-l";
    arg[1] = '\0';

    if(execvp(arg[0],arg) == -1)
    {
        printf("Error in executing ls");
    }       

}
else //Parent
{               
    //redirect standard output to the file descriptor
    dup2(pfd_1[1],1);
    //Close the read end
    if(close(pfd_1[0] == -1))
    {
        printf("Error in closing the read end from parent");
        exit(1);
    }
    //Command 
    arg[0] = "ls";
    arg[1] = "/proc/1/status";
    arg[2] = '\0';

    if(execvp(arg[0],arg) == -1)
    {
        printf("Error in executing ls");
    }       
}

}

任何想法可能是错误的?为什么会考虑标准输入坏文件描述符?我的理解是,因为标准输入和读取结束文件描述符是别名所以厕所-l会读无论输出为从父进程。我需要做的scanf函数从标准输入读取?

Any idea what might be wrong? Why would it consider standard input as bad file descriptor? My understanding was since the stdin and read end file descriptor are aliases so the wc -l would read whatever the output is from the parent process. Do I need to do scanf to read from the stdin?

推荐答案

现在的问题是在这条线:

The problem is in this line:

if(close(pfd_1[1] == -1))

您正在关闭 pfd_1 [1] == -1 ,这是必然等于 0 (因为它们永远不会相等)。正确的路线很可能是:

You are closing the result of pfd_1[1] == -1, which is by necessity equal to 0 (as they will never be equal). The correct line would probably be:

if (close(pfd_1[1]) == -1)

请注意,您在试图关闭读端在父进程再做这一点。

Note that you do this again later in attempting to close the read end in the parent process.

这篇关于如何使用管道运行命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆