以前、Cでfork()とパイプを使用 することについて質問を投稿しました。通常のtxtファイルを読み取り、ファイル内の単語を並べ替えるように、デザインを少し変更しました。これまでのところ、これは私が思いついたものです:
for (i = 0; i < numberOfProcesses; ++i) {
// Create the pipe
if (pipe(fd[i]) < 0) {
perror("pipe error");
exit(1);
}
// fork the child
pids[i] = fork();
if (pids[i] < 0) {
perror("fork error");
} else if (pids[i] > 0) {
// Close reading end in parent
close(fd[i][0]);
} else {
// Close writing end in the child
close(fd[i][1]);
int k = 0;
char word[30];
// Read the word from the pipe
read(fd[i][0], word, sizeof(word));
printf("[%s]", word); <---- **This is for debugging purpose**
// TODO: Sort the lists
}
}
// Open the file, and feed the words to the processes
file_to_read = fopen(fileName, "rd");
char read_word[30];
child = 0;
while( !feof(file_to_read) ){
// Read each word and send it to the child
fscanf(file_to_read," %s",read_word);
write(fd[child][1], read_word, strlen(read_word));
++child;
if(child >= numberOfProcesses){
child = 0;
}
}
ここnumberOfProcesses
で、はコマンドライン引数です。つまり、ファイル内の各単語を読み取り、それをプロセスに送信します。ただし、これは機能しません。子プロセスで単語を印刷すると、正しい出力が得られません。パイプとの間で単語を正しく読み書きしていますか?