Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do command line arguments work?

As the question mentions, how do command line arguments work in C(in general any language). The logical explanation I could think of is, the operating system sets some kind of environmental values for the process when it starts. But if it's true I should not be able to access them as argp[i] etc(I modified the main to expect the 2nd argument as char **argp instead of **argv). Please explain.

like image 948
Thunderman Avatar asked Dec 09 '22 02:12

Thunderman


1 Answers

I'll try to explain the implementation a bit more than other answers.
I'm sure there are inaccuracies, but hope it describes the relevant parts well enough.

Under the shell, you type ./myprog a b c.
The shell parses it, and figures out that you want to run ./myproj with three parameters.
It calls fork, to create a new process, where ./myprog would run.
The child process, which still runs the shell program, prepares an array of 5 character pointers. The first will point to the string ./prog, the next three are to the strings a, b and c, and the last is set to NULL.
Next, it calls the execve function, to run ./myprog with the parameter array created.
execve loads ./myprog into memory, instead of the shell program. It releases all memory allocated by the shell program, but makes sure to keep the parameter array.
In the new program, main is called, with the parameter array passed to it as argv.

like image 100
ugoren Avatar answered Dec 28 '22 07:12

ugoren