wrote On 09/01/06 15:55,:
> What am I doing wrong?
Three or four things that I can see. First, you're
asking Unix questions in a C newsgroup. Unix people tend
to know a fair amount about C and a reasonable number of
C people have some familiarity with Unix, but the two are
not synonomous. Do you ask questions about the vitamin
content of broccoli at an apple-growers' convention?
However, most of your mistakes are C mistakes, so we
may as well try to address them here.
> OUTPUT:
> % ./sysconf.sun4x_59
> Pages: 262144
> Page size KB: 8192
> Physical Memory: -1
> %
>
> CODE:
> /* sysconf.c */
> #include <unistd.h>
> #include <stdio.h>
>
> int main(void) {
> unsigned long long int physmem;
>
> printf("Pages: %d\n", sysconf(_SC_PHYS_PAGES));
Error of omission: Like many system calls and library
functions, sysconf() can fail. As is common practice, it
indicates its failure by returning a special value (-1, in
this case). You should check for that special value before
plowing blindly ahead; better to announce "I can't tell how
many pages there are" than to say "This machine has -1 pages!"
> printf("Page size KB: %d\n", sysconf(_SC_PAGESIZE));
> physmem = sysconf(_SC_PHYS_PAGES) * sysconf(_SC_PAGESIZE) / 1000;
You've gone to the trouble of using a `long long' for the
physmem variable, presumably because you expect the amount of
memory on the machine might exceed the capacity of a `long'.
Fine, but you haven't quite finished the job. Each of the
sysconf() calls returns a `long', and then you multiply those
together, and then you divide the product by a thousand, and
only then do you finally promote the result to `long long'.
All the arithmetic is carried out in plain `long', and if the
product was too large for `long' the damage has already been
done before the promotion. You'll need to convert one or both
of the sysconf() values to `unsigned long long' *before* trying
to multiply them; afterwards, it's too late.
> printf("Physical Memory: %d\n", physmem);
Do you know what kind of value the "%d" conversion requires?
Well, I'll tell you: it requires an `int'. What have you fed
it? An `unsigned long long'. "Size matters."
Error of omission: You've declared main() correctly, saying
that it returns an `int' value. Well, what `int' value would
you like it to return? (There is a special dispensation in the
latest compilers that lets you get away with this, but not all
compilers are so up-to-date or so lenient. Bad idea to rely
on a safety net that might not be there ...)
> }
--