いくつかの子プロセスとの双方向通信を必要とするアプリケーションを構築しています。私の親は、stdin から常に単語を読み取り、それを各子プロセスに渡すクエリ エンジンのようなものです。子プロセスは処理を実行し、専用パイプで親に書き戻します。
これは理論的には機能するはずですが、実装の詳細にこだわっています。最初の問題は、子をフォークする前に 2 つのパイプを作成することですか? フォークすると、子が親のファイル記述子のセットを継承することがわかります。これは、4 つのパイプが作成されるか、単純な 2 つのパイプが複製されることを意味しますか。それらが子で複製されている場合、これは、子でファイル記述子を閉じると、親のファイル記述子も閉じることを意味しますか?
私の理論は次のとおりです。明確にする必要があり、正しい方向に進む必要があります。これはテストされていないコードです。私が考えていることを理解してもらうために書いただけです。ありがとう、助けていただければ幸いです。
int main(void){
int fd[2][2]; //2 pipes for in/out
//make the pipes
pipe(fd[0]); //WRITING pipe
pipe(fd[1]); //READING pipe
if(fork() == 0){
//child
//close some ends
close(fd[0][1]); //close the WRITING pipe write end
close(fd[1][0]); //close the READING pipe read end
//start the worker which will read from the WRITING pipe
//and write back to the READING pipe
start_worker(fd[0][0], fd[1][1]);
}else{
//parent
//close the reading end of the WRITING pipe
close(fd[0][0]);
//close the writing end of the READING pipe
close(fd[1][1]);
//write data to the child down the WRITING pipe
write(fd[0][1], "hello\n", 6);
//read from the READING pipe
int nbytes;
char word[MAX];
while ((nbytes = read(fd[1][0], word, MAXWORD)) > 0){
printf("Data from child is: %s\n", word);
}
}
}