Printing Environmental Variables and CPU Time using C
To print the environmental variables of Linux using C. To print the system uptime and system idle time.
Suse Linux (Sun V20Z Linux Server)
Linux provides each running program with an environment. The environment is a collection of variable/value pairs. Both environment variable names and their values are character strings. By convention, environment variable names are spelled in all capital letters. You're probably familiar with several common environment variables already.
USER contains your username.
HOME contains the path to your home directory.
PATH contains a colon-separated list of directories through which Linux searches
for commands you invoke.
DISPLAY contains the name and display number of the X Window server on
which windows from graphical X Window programs will appear.
//Printing the Execution Environment
/* The ENVIRON variable contains the environment. */
extern char** environ;
int main ()
for (var = environ; *var != NULL; ++var)
printf ("%s\n", *var);
// printing the uptime and idle time
/* Summarize a duration of time to standard output. TIME is the
amount of time, in seconds, and LABEL is a short descriptive label. */
void print_time (char* label, long time)
/* Conversion constants. */
const long minute = 60;
const long hour = minute * 60;
const long day = hour * 24;
/* Produce output. */
printf ("%s: %ld days, %ld:%02ld:%02ld\n", label, time / day,
(time % day) / hour, (time % hour) / minute, time % minute);
int main ()
double uptime, idle_time;
/* Read the system uptime and accumulated idle time from /proc/uptime. */
fp = fopen ("/proc/uptime", "r");
fscanf (fp, "%lf %lf\n", &uptime, &idle_time);
/* Summarize it. */
print_time ("uptime ", (long) uptime);
print_time ("idle time", (long) idle_time);
The program can be compiled using gcc compiler
$: vi <filename.c>
$: gcc –o <linkname> <filename.c>