Program Arguments
When a Linux program written in C runs, it starts at the function main. This is declared as:
int main(int argc, char *argv[])
where argc is a count of the program arguments and argv is an array of character strings representing the arguments themselves.
Whenever the operating system starts a new program, the parameters argc and argv are set up and passed to main. These parameters are usually supplied by another program, very often the shell that has requested that the operating system start the new program. The shell takes the command line that it’s given, breaks it up into individual words, and uses these for the argv array.
For example, if we give the shell the following command, $ tom, shane, cat ‘and space’ the program myprog will start at main with parameters:
argc: 4
argv: {"tom", "shane", "cat", "and space"}
Note that the argument count includes the name of the program itself and the argv array contains the program name as its first element, argv[0]. Because we used quotes in the shell command, the fourth argument consists of a string containing spaces.
Command line arguments are useful for passing information to programs. For example, we could use them in a database application to pass the name of the database we wish to use, which would allow us to use the same program on more than one database.
Tuesday, October 7, 2008
Subscribe to:
Comments (Atom)