【问题标题】:Creating a Linux pipe using C++使用 C++ 创建 Linux 管道
【发布时间】:2014-11-08 13:50:00
【问题描述】:

我正在尝试创建一个包含管道和重定向的简单 shell 程序。对于管道,我目前有以下代码:

//****Contains Prompts for User Input outside of 'If' statement********

if( contains(userInput, '|', str1, str2));

//Fork a child process
pid_t pid1 = fork();
if (pid1 == 0) {

//First child creates the pipe
pipe(pipeFD);

    //First child forks to a second child
    pid_t pid2 = fork();
    if(pid2 == 0){

    //Replaces standard output with pipe input
    dup2(pipeFD[1], 1);


    //Executes first command
    parseArgs(str1, argv);
    execvp(argv[0],argv);
    }else{wait(NULL);}

//Back in first child

    //Fork a third child
    pid_t pid3 = fork();
    if(pid3 == 0){

    //Third child replaces standard input with pipe output
    dup2(pipeFD[0],0);

    //Third child executes the second command
    parseArgs(str2, argv);
    execvp(argv[0],argv);
    exit(EXIT_FAILURE);
    }else{wait(NULL);}

  }
}

就目前而言,我一直在使用 ls|grep 作为我的管道测试。输出应如下所示:

ls|grep hello
hello.cpp
helloworld.cpp
helloworld2.cpp
Enter a command:

相反,它看起来像这样:

ls|grep hello
Enter a command: hello.cpp
helloworld.cpp
helloworld2.cpp

【问题讨论】:

  • 研究现有的 Linux shell:大多数是免费软件,所以你应该下载并研究源代码(例如bash...)。你也可以使用strace。另请阅读Advanced Linux Programming
  • 目前还不清楚您的程序在做什么,仅给出部分来源。此外,lsgrep 都是现有程序,您希望如何调用您的程序也不清楚。
  • 据我所知,主程序在输出Enter a command之前并没有为孩子们提供wait
  • Geza Torok - 这也是我得出的结论,但是我不确定在哪里放置 wait() 来解决这个问题。

标签: c++ linux shell pipe


【解决方案1】:

好的,我知道出了什么问题!事实证明,我试图通过将 2 个子进程嵌套在一个子进程中来做太多事情。我已经改进了我的管道流程,只需要父流程中的 2 个子流程,它现在可以按预期工作:

 //Pass UserInput into the contains function to see if a pipe or redirect was used
if ( contains(userInput, '|')){

  split(userInput, '|', str1, str2);
  pipe(pipeFD);

    //Shell forks first child process
    pid_t pid1 = fork();
    if(pid1 == 0){

//First Child replaces standard output with pipe input
dup2(pipeFD[1],1);

//First Child Executes the first command
parseArgs(str1, argv);
execvp(argv[0],argv);

//Exit if execvp returns
exit(EXIT_FAILURE);
}

//Shell forks second child process
pid_t pid2 = fork();
if (pid2 == 0){

//Second Child replaces standard input with pipe output
    dup2(pipeFD[0],0);

//Second Child Executes the second command
parseArgs(str2, argv);
execvp(argv[0],argv);
exit(EXIT_FAILURE);
}else{wait(0);}

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-01
    • 1970-01-01
    • 2020-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    相关资源
    最近更新 更多