[Previous]
[Contents]
[Next]

main()

the function where program execution begins

Synopsis:

int main( void );
int main( int argc, const char *argv[] );
int main( int argc, const char *argv[], 
          char *envp[] );

Description:

The main() function is supplied by the user and is where program execution begins. The command line to the program is broken into a sequence of tokens separated by blanks, and are passed to main() as an array of pointers to character strings in the parameter argv. The number of arguments found is passed in the parameter argc.

The first element of argv is a pointer to a character string containing the program name. The last element of the array pointed to by argv is a NULL pointer (that is argv[argc] is NULL). Arguments that contain blanks can be passed to main() by enclosing them in double quote characters (which are removed from that element in the argv vector).

The command line arguments can also be obtained in their original format by using the getcmd() function.

The envp argument points to an array of pointers to character strings that are the environment strings for the current process. This value is identical to the environ variable, which is defined in the <stdlib.h> header file.

Returns:

An exit code back to the calling program (usually the operating system).

Examples:

#include <stdio.h>

int main( int argc, char *argv[] )
  {
    int i;
    for( i = 0; i < argc; ++i ) {
      printf( "argv[%d] = %s\n", i, argv[i] );
    }
    return( 0 );
  }

produces the output:

argv[0] = mypgm
argv[1] = hhhhh
argv[2] = another arg

when the program mypgm is executed with the command:

mypgm hhhhh  "another arg"

Classification:

ANSI

Safety:
Interrupt handler No
Signal handler No
Thread Read the Caveats

Caveats:

The main() function is thread-safe only if you make it so.

See also:

abort(), atexit(), _bgetcmd(), close(), exec... functions, exit(), _exit(), getcmd(), getenv(), onexit(), putenv(), sigaction(), signal(), spawn... functions, system(), wait(), waitpid()


[Previous]
[Contents]
[Next]