Vindhya G
Vindhya G

Reputation: 1369

Invocation of C program in shell

In the K&R book there is a question as following:

Write a program that converts uppercase to lower and vice versa, depending on the name it is invoked with?

In the solution given, it says that when the program is invoked with the name lower, the program converts lower to upper. In the solution program argv[0] is compared with "lower" but on Linux argv[0] will be "./lower" and not "lower".

Could someone clarify that please?

Upvotes: 2

Views: 225

Answers (2)

Tanmoy Bandyopadhyay
Tanmoy Bandyopadhyay

Reputation: 985

How does Shell executes your program? (Very simple explanation below)

shell()
{
  loader("Path name/Filename of your program", argv[0], argv[1]...for your program);
}

That means all those arguments to the loader, is made by the shell and then the loader is invoked and by default argv[0] is made the same as the Path name/File name of program.

Now when do say ./a.out ..it means absolute path name of your program is ./a.out.(The file a.out in the current directory)

Can we omit ./? The answer is yes, if the environmental variable PATH is having . as one of its component say the first component.

You may see the content of PATH variable by typing echo $PATH in the shell prompt.(A : separated list of paths will be seen).

if . is not there you may add that by typing export PATH=.:$PATH in the shell prompt.

After this you may run your code from the current directory by typing a.out and need not have to type ./a.out.

Now I think this is clear that why argv[0] becomes the name of the file that you are executing?

Now can we have a different name for argv[0] and not the filename?

The answer is yes and then you need to call the loader yourself, that is write a small piece of code that behaves like shell.

You may browse the internet / man page for the execve family of functions, which is actually the loader referred here.

Upvotes: 3

djconnel
djconnel

Reputation: 431

Consider this test code:

#include <stdio.h>
int main(int argc, char** argv) {
  printf("ARGV[0] = %s\n", argv[0]);
}

If I compile it as "test_argv", and run it, I get whatever I typed to run the program:

% ./test_argv
ARGV[0] = ./test_argv
% test_argv
ARGV[0] = test_argv
% /tmp/test_argv
ARGV[0] = /tmp/test_argv

So you want to test the string, for example, against a regular expression, or for a substring.

Upvotes: 3

Related Questions