Sunday, September 18, 2016

Unix Internals - With C Programming Examples-2

Print all the environment variables using the envp argument in main() function.


/* Program to Print Environment Variables
 * Program Name : prenv.c
 *
 */
#include <stdio.h>
int main(int argc, char *argv[], char *envp[])
{
    int i = 0;

    while (envp[i]) {
        printf("Environment Variable : %s\n", envp[i]);
        i++;
    }
    return 0;
}



Print all the environment variables using extern variable environ.

/* Program to Print Environment Variables
 * Program Name : prenvv.c
 *
 */
#include <stdio.h>

extern char **environ;

int main(int argc, char *argv[])
{
    int i = 0;

    while (environ[i]) {
        printf("Environment Variable : %s\n", environ[i]);
        i++;
    }
    return 0;
}


The output of both the programs are same.

Program Output:


$ ./prenv
Environment Variable : _=./prenv
Environment Variable : HZ=100
Environment Variable : SSH_TTY=/dev/ttyp0
Environment Variable : PATH=/bin:/usr/bin:/usr/gnu/bin:/sbin:/usr/local/bin
Environment Variable : HUSHLOGIN=FALSE
Environment Variable : EDITOR=emacs
Environment Variable : SHELL=/bin/ksh
Environment Variable : HOME=/home/reemus
Environment Variable : TERM=xterm
Environment Variable : PWD=/home/reemus/prog/cprog
Environment Variable : TZ=EST5EDT
Environment Variable : ENV=/home/reemus/.kshrc
$


Thursday, September 15, 2016

Unix Internals - With C Programming Examples-1

For a long time I wanted to create a series of Blog post of what I have learned as Unix System Programming and its Internals with the help of plain simple to read examples.

Program: cmdargs.c


/* Program to read and display the command-line arguments */
#include <stdio.h>

int main(int argc, char *argv[])
/* argc - No. of Command-line Arguments passed to the program */
/* argv - Array of Strings - Command-line Arguments */
{
    int i;
    printf("No. of Command-line Arguments : %d\n", argc);
    for (i = 0; i < argc; i++) {
        printf("Arg[%d] = %s\n", i, argv[i]);
    }
    return 0;
}

Output:


$ ./cmdargs one two three
No. of Command-line Arguments : 4
Arg[0] = ./cmdargs
Arg[1] = one
Arg[2] = two
Arg[3] = three
$ 

As you can see the "argc" contains the number of command-line arguments passed to the program.

The very first command-line argument for the program is program name itself, followed by the other arguments passed.