getopt reinvocation/reentrancy

Joel Sherrill
Fri Feb 29 00:21:00 GMT 2008

Gregory Pietsch wrote:
> I tried to add the reentrant functions to the getopt implementation.
> Please check it out and if it's okay, patch away. -- Gregory Pietsch
It doesn't work for me.  I have attached a test which I
hacked together which I think shows the failure.  It could
be me but you have a test anyway.  I hacked a bit to
get it to compile natively on Fedora but use the RTEMS
shell make args and call a main() a couple of times.

A quick look at the shows the old global variables
are still in getopt.c.

Thanks for the quick turn around.
> Joel Sherrill wrote:
>> Hi,
>> We have been working on the RTEMS Shell and
>> I noticed something that I don't know how to
>> properly deal with.  I am sure it is beyond
>> the requirements of opengroup.
>> RTEMS applications are usually a single statically
>> linked executable so there can only be one main.
>> So we have main's for each command (e.g. main_cat(),
>> main_cp(), main_cpuuse(), etc.).  Each main_XXX
>> is passed an argc, argv set and may use getopt()
>> to interpret it.
>> The problem is that newlib's getopt() uses global
>> variables to hold state as the arguments are parsed.
>> That is the crux of the reentrancy issue.
>> If you invoke getopt() to parse a second set of
>> options, the state information on the second set
>> is left over from the end of parsing the first set.
>> In the case I discovered this, I was doing this:
>> netstats -c -u -i
>> netstats -t
>> On the second netstats invocation, the state pointed
>> passed the end of the set of arguments so nothing
>> was parsed.
>> I am looking for suggestions on how to enhance
>> getopt to support this type of usage.  I do not
>> see getopt_r in /usr/include on Fedora 8 but Google
>> shows that glibc had this type of functionality at
>> one point.  I think the minimum requirement is a
>> parallel set of getoptXXX_r with a state variable that
>> can be initialized by the user.
>> I also noticed that stdlib/getopt.c has multiple
>> public API functions in it.  Should these be broken
>> out?  I know they are individually small but....
>> Any thoughts?

Joel Sherrill, Ph.D.             Director of Research & Development        On-Line Applications Research
Ask me about RTEMS: a free RTOS  Huntsville AL 35805
   Support Available             (256) 722-9985

-------------- next part --------------
A non-text attachment was scrubbed...
Name: getopt-test.tar.bz2
Type: application/x-bzip
Size: 8213 bytes
Desc: not available
URL: <>

More information about the Newlib mailing list