in src/oscounter.c [166:225]
uint64_t read_counter_from_proc(char *file_name, char *section, char *key)
{
char *log;
FILE *stream;
char *line = NULL, *pch = NULL;
size_t len = 0;
ssize_t read;
int key_found = 0;
uint64_t ret = 0;
stream = fopen(file_name, "r");
if (!stream) {
ASPRINTF(&log, "failed to open file: %s. errno = %d", file_name, errno);
PRINT_ERR_FREE(log);
return 0;
}
/*
* example:
*
* Tcp: ... OutSegs RetransSegs InErrs OutRsts InCsumErrors
* Tcp: ... 8584582 27 0 5 0
*
* the first line contains the key;
* if a key is found, then,
* read the corresponding cell as value from next line
*/
while ((read = getline(&line, &len, stream)) != -1) {
/* key is found, then read the value here */
if (key_found > 0) {
pch = line;
while ((pch = strtok(pch, " "))) {
key_found--;
if (key_found == 0) {
ret = strtoull(pch, NULL, 10);
goto found;
}
pch = NULL;
}
}
/* try to locate the key */
if (strcmp(section, line) < 0) {
if (strstr(line, key) != NULL) {
pch = line;
while ((pch = strtok(pch, " "))) {
key_found++;
if (strcmp(pch, key) == 0)
break;
pch = NULL;
}
}
}
}
found:
free(line);
fclose(stream);
return ret;
}