execvp を使用して ls|wc を実行しようとしています。そこで、パイプを作成してからフォークして子を作成します。親/子の適切な (読み取り/書き込み) エンドを閉じてから、もう一方のエンドを stdout/stdin にマップします。次に、execvp を使用して親で ls を実行し、子で wc を実行します。プログラムを実行すると、
wc:standard input:bad file descriptor.
0 0 0
wc: -:Bad file descriptor
これが私のコードです:
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");
}
}
}
何が間違っているのでしょうか?標準入力を不適切なファイル記述子と見なすのはなぜですか? 私の理解は、標準入力と読み取り終了ファイル記述子がエイリアスであるため、 wc -l は親プロセスからの出力を読み取るためです。標準入力から読み取るには scanf を実行する必要がありますか?