[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: getloadavg and proc filesystem

> > I looked at the implementation of getloadavg to see how 'real
> > programmers' used
> > the proc filesystem. I do not see how the implementation (in glibc)  is
> > protected
> > from the kernel changing the data underneath
>it while it is being  read....

Hi, it shouldn't happen for getloadavg.

static int loadavg_read_proc(char *page, char **start, off_t off,
         int count, int *eof, void *data)
  int a, b, c;
  int len;

  a = avenrun[0] + (FIXED_1/200);
  b = avenrun[1] + (FIXED_1/200);
  c = avenrun[2] + (FIXED_1/200);
  len = sprintf(page,"%d.%02d %d.%02d %d.%02d %ld/%d %d\n",
    LOAD_INT(a), LOAD_FRAC(a),
    LOAD_INT(b), LOAD_FRAC(b),
    LOAD_INT(c), LOAD_FRAC(c),
    nr_running(), nr_threads, last_pid);
  return proc_calc_metrics(page, start, off, count, eof, len);

The callback even ignores the "count" variable so
it expects to be able to write all of its data at once.
(it uses sprintf and not snprintf).

When you read from /proc, the kernel calls a callback.
The callback writes the data to a buffer and then the function
ends. So, when you open the file in user space,
the kernel will write most of the data to the buffer,
and if the statistics change, you will still reference the
data written by the callback.

(it's not like a static string in libc or something like that).

Something might happen if the /proc entry is big.
In this case, things get more complicated and
I still don't understand the details. I'm a newbie.

> >
> > ie: getloadavg open /proc/loadavg for O_RDONLY
> >     getloadavg reads the first 4 bytes
> >     kernel completely updates the file
> >     getloadavg reads the rest of file.....
> >
> > And as /proc/stat is bigger, the problem is likely to occur even more
> > often?!
> > Or am i just being stupid?
> >

I'm not expert either. These days I'm learning how
to create /proc entries, and I'll start with one that's
read only.

It will return the number of keys pressed so I can
so something like this : http://bodq.vstu.edu.ua/activity/

This patch adds "/proc/kstrokes" (currently, it only works
inside User Mode Linux, I'll port it soon to use the real


I will have to return the number of keys pressed modulo
100 to protect the user's privacy. (I will use in my desktop
machine). I'm planning to get statistics for A-Z keys.

I Hope it helps.

Homepage : http://geocities.com/arhuaco

The first principle is that you must not fool yourself
and you are the easiest person to fool.
     -- Richard Feynman.

Reply to: