7.5 Invocation Command-line Parameters

When a command issued to the system shell invokes a program, including a user's program, a number of parameters can be passed to that program from the command-line. These command-line parameters or command-line arguments are accessible within the user program as follows:

C program: In the header of the main(int argc, char *argv[]), argc gets from the shell the number of command-line arguments, which include the invocation name of the program as one of them. Thus, the value of argc is one plus the number of actual arguments. The arguments are accessible simply as argv[1], argv[2], etc. Further, it is possible that the arguments may be a mix of program options and other arguments. To easily handle such a situation, a library function getopt is available which help parse the command-line arguments and separate out the options.

Java programs: The command-line arguments are available via the main (String[] args) header.

Perl programs: In a Perl program, the command-line arguments are available as $ARGV[0], $ARGV[1], etc. Unlike a C program, $ARGV[0] is the first actual command-line argument.

Assembly language program: The shell passes the command-line arguments to an assembly program just like it does for a C, Java or Perl program. However, the assembly program has to obtain the arguments a bit more “painfully”. We give here a sample assembly program to illustrate this:

.section .data
// Command table to store upto 10 command-line arguments 
   cmd_tbl:
     .rept 10 
        .long 0
     .endr 
.section .text 
   .globl _start 
   _start:
// Set up the stack frame
    movl %esp, %ebp 
// Top-of-stack contains the number of command-line arguments.
// The default value is 1
    movl (%ebp), %ecx 
// Exit if arguments are more than 10
     cmpl $10, %ecx
     jg      _exit
     movl $1, %esi
     movl $0, %edi 
//Store the command-line arguments in the command table
  store_loop:
     movl (%ebp, %esi, 4), %eax
     movl %eax, cmd_tbl( , %edi, 4)
     incl %esi
     incl %edi
     loop store_loop // decr ecx, Loop if Not Zero 
// access the command-line arguments 
   _exit:
     movl $1, %eax
     movl $0, %ebx
     int  $0x80
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.47.166