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.
As the question mentions, how do command line arguments work in C(in general any
Share
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
./myprojwith three parameters.It calls
fork, to create a new process, where./myprogwould 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 stringsa,bandc, and the last is set to NULL.Next, it calls the
execvefunction, to run./myprogwith the parameter array created.execveloads./myproginto 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,
mainis called, with the parameter array passed to it asargv.