我不會說謊。這是一個家庭作業問題。然而,就我而言,寶貝已經沒有了。現在,我只是在尋找答案,因爲我想 - 我可能會瘋了。玩具外殼沒有正確配管
該程序的目標是以類似於shell的方式執行命令ps -A | grep (inputstring) | wc -l
。所以,我產生了這些流程,讓他們彼此等待。最新的過程,曾孫,execlp("ps","ps","-A",NULL)
,它取代了ps -A
過程。在execlp
之前,我確定它的標準輸出正在輸出管道。下一個進程是wait()
ing,並且已經自己設置,以便輸入管道進入標準輸入,並且標準輸出進入輸出管道,並且它將執行grep等等。
我幾乎是積極的我把它設置正確。然而...程序確實如此。不。工作。
#include <stdlib.h>
#include <iostream>
#include <string>
#define MAXLINE 1500
#define READ 0
#define WRITE 1
using namespace std;
int main(int argc, char** argv) {
//* start of input block
if (argc != 2) {
cout << "Usage: ./a.out arg1" << endl;
return 0;
}
string in = argv[1];
// end of input block */
int pipeA[2], pipeB[2], pid, stat;
// get our first set of pipes
if (pipe(pipeA) < 0) {
cerr << "Pipe error.\n";
exit(-1);
}
if (pipe(pipeB) < 0) {
cerr << "Pipe error.\n";
exit(-1);
}
// make the first fork
if ((pid = fork()) < 0) { cerr << "Fork error.\n"; exit(-1); }
if (pid > 0) { // parent case
wait(&stat);
} else { // child case
if ((pid = fork()) < 0) { cerr << "Fork Error\n"; exit(-1); }
if (pid > 0) { // child
wait(&stat);
dup2(pipeA[READ],READ);
execlp("wc","wc","-l",NULL);
} else { // grand-child
if ((pid = fork()) < 0) { cerr << "Fork Error\n"; exit(-1); }
if (pid > 0) { // still grand-child
wait(&stat);
dup2(pipeB[READ],READ);
dup2(pipeA[WRITE],WRITE);
close(pipeB[READ]);
execlp("grep","grep",in.c_str(),NULL);
} else { // great grand-child
dup2(pipeB[WRITE],WRITE); // t now goes to pipeB[1]
close(READ);
close(pipeB[READ]);
execlp("ps", "ps", "-A", NULL);
}
}
}
return 0;
}
編輯:更改爲我的代碼的雙管變體。
它是如何工作的?分段故障?錯誤訊息?錯誤的輸出?沒有輸出或未經過濾的'ps'或其他東西的輸出? – sth
你不應該讓你的子進程等待任何東西。 –
此外,父進程應分叉兩個孩子(應該沒有孫子)。 –