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.


GCC compiler

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.

For instance:

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

#include <stdio.h>

/* The ENVIRON variable contains the environment. */

extern char** environ;

int main ()


char** var;

for (var = environ; *var != NULL; ++var)

printf ("%s\n", *var);

return 0;


// printing the uptime and idle time

#include <stdio.h>

/* 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 ()


FILE* fp;

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);

fclose (fp);

/* Summarize it. */

print_time ("uptime ", (long) uptime);

print_time ("idle time", (long) idle_time);

return 0;




The program can be compiled using gcc compiler

$: vi <filename.c>

$: gcc –o <linkname> <filename.c>


Popular Posts