FYI: struggling with 'int optind'

Bernd Petrovitsch bernd at petrovitsch.priv.at
Fri May 3 09:29:22 UTC 2013


Hi!

On Don, 2013-05-02 at 23:28 +0200, Lambrecht Jürgen wrote:
> On 05/02/2013 03:57 PM, Bernd Petrovitsch wrote:
[...]
> > What has the getopt() library function - which is the only one which
> > uses "optind" - to do with a shell?
> Busybox code is full of lines like this:
>        argv += optind;

That's a typical pattern for post-getopt() code: You simply move the
argv over the already analyzed parameters (the ones with a "-" in front
of them) of the program so that only the list of files (or whatever)
remains.
Going back to the original mail: That was an compiler message so
probably just some #include line is missing somewhere.

> What I mean with a shell is that that 'argv' are (or contains or points 
> to ..) the arguments of a program one can call in a shell (like ash, sh, 
> bash).

"argv" is usually the second parameter in the main() function - be it a
shell or "grep" or whatever.

> So because of the shell, one has to pass arguments to a program via 
> argc/argv, and there that optind is used.

Actually all programs behave that way since one can pass parameters to
all programs.

> When I think of it, my question is probably stupid, because BusyBox 
> "provides replacements for most of the utilities you usually find in GNU 
> fileutils, shellutils, etc."
> The utilities are meant to be called from a shell, not from another c 
> program (as a function).

Yes, because they are programs. That makes them not different to GNU- or
any other tools: "called from a shell" actually means "fork()+execve()"
and the execve() gets the parameters.
It is  - for the called program - no difference if some shell does or
some random program does that.
Disclaimer: Assuming a MMU and virtual memory - I don't know about Ecos.
But fork()+execve() should work on no-MMU systems too.

	Bernd
-- 
Bernd Petrovitsch                  Email : bernd at petrovitsch.priv.at
                     LUGA : http://www.luga.at



More information about the busybox mailing list