[LTP] [PATCH] lib: add tst_read_meminfo / tst_get_avail_mem

Jan Stancek
2016-07-13T14:13:13Z

----- Original Message -----
> From: "Cyril Hrubis" <chrubis@suse.cz>
> To: "Jan Stancek" <jstancek@redhat.com>
> Cc: "Li Wang" <liwang@redhat.com>, ltp@lists.linux.it
> Sent: Wednesday, 13 July, 2016 3:54:28 PM
> Subject: Re: [LTP] [PATCH] lib: add tst_read_meminfo / tst_get_avail_mem
>
> Hi!
> > Latest idea attached.
> >
> > It's similar to SAFE_FILE_SCANF, but it scanfs each line and first
> > matching all scanf directives wins and terminates search, otherwise
> > you get non-zero ret code. For example:
> >
> > if (SAFE_FILE_LINES_SCANF("/proc/meminfo", "MemFree: %ld", &free))
> > tst_brk(TBROK, "Could not parse MemFree");
>
> The API looks good to me. Nice work.
>
> We should call this version FILE_LINES_SCANF() since the SAFE_ variants
> call tst_brkm() on failure.

I was hesitant about SAFE_ part, but since it still calls brk on some
occasions I left it there.

There is also option to remove brkm calls, turn it into tst_file_lines_scanf(),
and let user deal with possible errors.

>
> > diff --git a/lib/safe_file_ops.c b/lib/safe_file_ops.c
> > index dff85cd83fec..db1660b1f684 100644
> > --- a/lib/safe_file_ops.c
> > +++ b/lib/safe_file_ops.c
> > @@ -169,6 +169,49 @@ void safe_file_scanf(const char *file, const int
> > lineno,
> > }
> > }
> >
> > +
> > +/*
> > + * Try to parse each line from file specified by 'path' according
> > + * to scanf format 'fmt'. If all fields could be parsed, stop and
> > + * return 0, otherwise continue or return 1 if EOF is reached.
> > + */
> > +int safe_file_lines_scanf(const char *file, const int lineno,
> > + void (*cleanup_fn)(void),
> > + const char *path, const char *fmt, ...)
> > +{
> > + FILE *fp;
> > + int ret = 0;
> > + int arg_count = 0;
> > + char line[BUFSIZ];
> > + va_list ap;
> > +
> > + if (!fmt) {
> > + tst_brkm(TBROK, cleanup_fn, "pattern is NULL, %s:%d",
> > + file, lineno);
> > + }
> > +
> > + fp = fopen(path, "r");
> > + if (fp == NULL) {
> > + tst_brkm(TBROK | TERRNO, cleanup_fn,
> > + "Failed to open FILE '%s' for reading at %s:%d",
> > + path, file, lineno);
> > + }
> > +
> > + arg_count = count_scanf_conversions(fmt);
> > +
> > + while (fgets(line, BUFSIZ, fp) != NULL) {
> > + va_start(ap, fmt);
> > + ret = vsscanf(line, fmt, ap);
> > + va_end(ap);
> > +
> > + if (ret == arg_count)
> > + break;
> > + }
> > + fclose(fp);
>
> I wonder if it would be easier to take the fmt and append "%*[^\n]\n" to
> it so that we can use fscanf() directly without the line buffer...
>
> I guess that both of these are similarily complicated.
>
> --
> Cyril Hrubis
> chrubis@suse.cz
>