あなたは、ファイルの第一の端部に到達すると、EOFのための入力ストリームフラグが設定されています。操作を再開する前にクリアする必要があります(clearerr(fp)
)。あなたは通常も眠るべきです。 (ストリームに関連付けられているファイルディスクリプタのlseek()
を使用することは助けにはなりません。)
はここにあなたのコードに基づいてプログラムだ - 私は(特に良い名前ではありません)PATHの値を変更する必要がありました:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define PATH "demo.txt"
int main(void)
{
FILE * fp;
char * line = NULL;
size_t len = 0;
fp = fopen(PATH, "r");
if (fp == NULL)
{
perror(PATH);
exit(EXIT_FAILURE);
}
while (1)
{
if (getline(&line, &len, fp) != -1)
printf("%s",line);
else
{
printf("EOF\n");
sleep(1);
clearerr(fp);
}
}
if (line)
free(line);
return(EXIT_SUCCESS);
}
ファイルにデータを生成するプログラムがある場合は、そのファイルでテストできます。 dribbler
へ
$ dribbler -f demo.txt -s 1.5 -r 0.5 &
[1] 20678
$ cat demo.txt
0: message written to file
1: message written to file
2: message written to file
$ tail11
0: message written to file
1: message written to file
2: message written to file
3: message written to file
4: message written to file
5: message written to file
EOF
6: message written to file
EOF
EOF
7: message written to file
EOF
8: message written to file
EOF
EOF
9: message written to file
EOF
10: message written to file
EOF
11: message written to file
EOF
EOF
^C
$
オプションがあります:私はことを行うプログラムdribbler
持っているので、
Usage: dribbler [-hlntV][-s nap.time][-r std.dev][-f outfile][-i infile][-m message][-o openstr][-F format]
-V Print version information and exit
-f outfile Write to named file (dribbler.out)
-h Print this help message and exit
-i infile Read lines from input file
-l Loop back to start of input file on EOF
-m message Write message on each line of output
-n Number lines read from input file
-o openstr Flags passed to fopen() (a+)
-s nap.time Sleep for given interval between writes (1.000 second)
-r std.dev Randomize the time (Gaussian around nap.time with std.dev)
-t Write to standard output instead of file
-F format Printf format to use instead of %zu
を、それはガウスランダムで、1.5秒の平均時間でファイルdemo.txt
に書いていました標準偏差が0.5秒の分布。 これは、出力の連続する行の間に2つのメッセージが表示されることがあります。
[こちら](https://stackoverflow.com/questions/5474232/how-to-loop-through-only-active-file-descriptors-from-fd-set-result-from-select) – phyloflash
ファイルの終わりに達したときにただちにスリープして再度読み込む必要はありません – Pras