我无法弄清楚为什么我可以成功地通过一个叉子进行管道,但不能通过2。第一个示例给出了预期的输出等效于" ps -a | grep bash"和第二个示例示例应给出" PS -A | Grep Bash | WC -L"的输出,这仅是第一个输出产生的线数。相反,它没有提供输出,只是悬挂。
这有效:
#include <iostream>
#include <string>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
using namespace std;
int main(int argc, char* argv[])
{
int p1[2], p2[2];
pipe(p1); pipe(p2);
pid_t pID;
pID = fork();
if (pID == 0)
{
close(p2[0]);
dup2(p2[1], 1);
close(p2[1]);
execlp("ps", "ps", "-A", 0); // print all processes
}
else
{
wait(pID);
close(p2[1]);
dup2(p2[0],0);
close(p2[0]);
execlp("grep", "grep", "bash", NULL); // search for bash (in process list)
}
}
但这不是:
#include <iostream>
#include <string>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
using namespace std;
int main(int argc, char* argv[])
{
int p1[2], p2[2];
pipe(p1); pipe(p2);
pid_t pID;
pID = fork();
if (pID == 0)
{
pID = fork();
if (pID == 0)
{
close(p2[0]);
dup2(p2[1], 1);
execlp("ps", "ps", "-A", 0); // print all processes
}
else
{
wait(pID);
close(p2[1]);
dup2(p2[0],0);
close(p1[0]);
dup2(p1[1], 1);
execlp("grep", "grep", "bash", 0); // search for bash (in process list)
}
}
else
{
wait(pID);
close(p1[1]);
dup2(p1[0],0);
execlp("wc", "wc", "-l", 0); // count lines
}
}
正如Moecoke和Leffeir所说,如果您更改代码中的一行,它的工作原理绝对可以。
#include <iostream>
#include <string>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
using namespace std;
int main(int argc, char* argv[])
{
int p1[2], p2[2];
pipe(p1);
pid_t pID;
pID = fork();
if (pID == 0)
{
pipe(p2); // <-- call pipe for p2 here ---
pID = fork();
if (pID == 0)
{
close(p2[0]);
dup2(p2[1], 1);
execlp("ps", "ps", "-A", 0); // print all processes
}
else
{
wait(pID);
close(p2[1]);
dup2(p2[0],0);
close(p1[0]);
dup2(p1[1], 1);
execlp("grep", "grep", "p", 0); // search for bash (in process list)
}
}
else
{
wait(pID);
close(p1[1]);
dup2(p1[0],0);
execlp("wc", "wc", "-l", 0); // count lines
}
}