我有这段代码将内存缓存记录到文件中:
void cache_dump(const int signal) {
rewind(cache_file); // this is ok, because the cache will never shrink
unsigned int n;
for (n = 0; n < cache_size; n++){
inet_ntop(AF_INET, &cache[n].device, device_buffer, INET_ADDRSTRLEN);
inet_ntop(AF_INET, &cache[n].remote.sin_addr, remote_buffer, INET_ADDRSTRLEN);
fprintf(cache_file, "%-15s %-15s %-5u %-lu\n", device_buffer, remote_buffer, ntohs(cache[n].remote.sin_port), cache[n].last_seen);
}
}
缓存中的结构如下所示:
struct cache_entry {
struct in_addr device;
struct sockaddr_in remote;
unsigned long last_seen;
};
其他信息:
device_buffer
和remote_buffer
char[INET6_ADDRSTRLEN]
对于ipv4地址来说足够大结果奇怪
随机地,结果文件将被破坏,如下所示:
10.13.14.247 10.12.19.240 31337 1472552078
10.13.14.248 10.12.11.244 31337 1472552079
10.13.14.249 10.12.11.237 313310.108.16.151 10.230.16.102 31337 1469798419
10.13.28.1 10.12.26.148 31337 1472551983
10.13.28.58 10.12.127.241 31337 1472552008
因此,一行会突然中断(没有新行)并与下一行合并。这很少发生,但仍然如此。它似乎与高系统负载有关,但在查看htop
之后,这是一个猜测。
有没有人遇到过这种奇怪的行为?
更新
缓存文件打开如下:
cache_fd = open(logpath, O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IRGRP | S_IROTH); // open for writing, empty, create if does not exist, set 444 rights
if (cache_fd == -1)
die("Failed to open cache file for writing!");
cache_file = fdopen(cache_fd, "w");
if (cache_file == NULL)
die("Failed to open cache file descriptor for writing!");