Operating Systems > Linux and UNIX

Well, I'm stupid..

<< < (3/3)

voidmain:

quote:Originally posted by Calum:
you raise a point i have just recently found out about and am still perplexed by! if you link to an application, how does it know what parameters to invoke? i mean this zcat link, how does bzip know?

--- End quote ---


This is a very cool feature of UNIX and C. In a program written in C any command line parameters that are passed to the program come in the form of an array called "argv[]". The number of command line parameters is stored in the integer variable "argc" (argument count). The first element of the argv[] array is the name of the program, the second element of the argv[] array is the first parameter passed to the program. So by checking "argv[0]" you can execute different code based on differing names of the program. Example:


--- Code: ---
--- End code ---

Copy that code into a file called "myname.c" and then compile it:

$ make myname

Run it by:

$ ./myname

Create a hard link:

$ ln myname yourname

Run the link:

$ ./yourname

As you can see, the program can figure out what it's name is easily and then branch off and execute different things based on what it's name is if you were to put some conditional statements in there (if, switch, etc).

Navigation

[0] Message Index

[*] Previous page

Go to full version