トラブルパイプライン3つのコマンド「dmesg | sort | more」c ++
質問
1つのコマンドの出力を別のコマンドの入力に正常に配管し、2番目のコマンドの出力を画面に表示しました。
3つの連続したコマンドでこれをやりたいです。 (実際、最終的には、実行時にプログラムに渡されたnコマンドでそれをやりたいです。
これは、3つのコマンドを一緒にパイプ化する私の試みです。
更新:最新の試みを反映するように質問を更新しました。
#include <string.h>
#include <fstream>
#include <iostream>
#include <unistd.h>
#include <stdio.h>
#include <sys/wait.h>
#include <sys/types.h>
using namespace std;
int main(int argc, char * argv[])
{
pid_t pid;
int pfd[2];
char* prgname = NULL;
if(pipe(pfd) == -1)
{
perror("error on pipe call");
return(1);
}
for(int j = 0;j<numberOfCommands;j++)
{
cout<<commands[j]<<"_"<<endl;
}
pid = fork();
if(pid == 0){//child process
close(pfd[0]); //close read end of pipe
dup2(pfd[1],1);//connect the pipes
close(pfd[1]);//close extra file descriptors
prgname = (char*)"dmesg"; //commands[0];//first command
execlp(prgname, prgname, 0);//Load the program
}
else
{
int pfd2[2];
if(pipe(pfd2) == -1)
{
perror("error on pipe call 2");
return(1);
}
pid = fork();
if(pid == 0)//child
{
close(pfd[1]);
dup2(pfd[0],0);
close(pfd[0]);
close(pfd2[0]);
dup2(pfd2[1],1);
close(pfd2[1]);
prgname = (char*)"sort";
execlp(prgname,prgname,0);
}
else
{
close(pfd2[1]); //close the write end of the pipe
dup2(pfd2[0],0);//connect the pipes
close(pfd2[0]); //close extra file descriptor
prgname = (char*)"more"; //commands[1];//now run the second command
execlp(prgname, prgname, 0);//Load the program
}
}
return 0;
}
シンプルさのためにすべての値をハードコード化しました。このプログラムは、「dmesg | more」の出力を表示しますが、一種の部分を実行してからフリーズします。左下にdmesgなどの物ggingいを見ていますが、これ以上見ることはできません。
何か案は?
解決
pipe(2)
1つのパイプに2つのファイル記述子のみを提供します。 3番目のファイル記述子(pfd[2]
)ジャンクであり、初期化されることはありません。 3つのコマンドが入ったパイプラインを作成する場合は、電話する必要があります pipe()
2つのパイプを取得するには、1つは1つ目と2番目のプロセスを接続するためのパイプ、もう1つは2番目と3番目のプロセスを接続するためです。
所属していません StackOverflow