私は、ユーザーが文字を入力しない限り、ファイルが終了するまでファイルをゆっくり(1秒間隔で)印刷する必要がある練習をしています。stdinノンブロッキングの作成
これまでのところ、プログラムは1秒間隔でファイルを出力しますが、文字を入力すると何も起こりません。私の推測では、何とか間違った選択をしています。
これは私が提出した最後のプログラムです。
#include <stdio.h>
#include <stdlib.h>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
int main(void)
{
FILE* infile;
char str[100];
fd_set readset;
struct timeval tv;
// open a file
if((infile = fopen("infile", "r")) == NULL)
{
(void)printf("Couldn't open the file\n");
exit(1);
}
// file was opened successfully
else
{
// while we are not at the end of a file
while(fgets(str, 100, infile) != NULL)
{
FD_ZERO(&readset);
FD_SET(fileno(stdin), &readset);
// set the time value to 1 second
tv.tv_sec = 1;
tv.tv_usec = 0;
select(fileno(infile)+1, &readset, NULL, NULL, &tv);
// the user typed a character so exit
if(FD_ISSET(fileno(stdin), &readset))
{
fclose(infile);
exit(0);
}
// the user didn't type a character so print the next line
else
{
fgets(str, 100, stdin);
puts(str);
}
}
// clean up
fclose(infile);
}
// report success
return 0;
}
ありがとうございました!
なぜ 'writeet'に' infile'を置いていますか?あなたはそれに書いていません。 – aschepler
良い点、これを反映するように更新します。 –
推測すると、 'infile'が読み取り専用で開かれたことを考えると' writeset'に 'infile'を持つのは良くないでしょう。しかし、これが問題を引き起こしているかどうかはわかりません。 –