问题
I have a C program which expects to be called with several options and 1 non-option argument (i.e. with no associated option letter), and uses getopt to parse these options. For example, it could be called with:
Example1:
myProgram -a "aParam" -b "bParam" "xParam"
I have been using SLES10, and the options worked in any order. For example, the non-option argument, "xParam" could come first:
Example2:
myProgram "xParam" -a "aParam" -b "bParam"
However, when testing in SLES11, it seems that getopt stops processing as soon as it reaches a non-option parameter, so example 2 above does not work.
I've read the getopt man pages and seen that this may be relevant:
If the first character of optstring is '+' or the environment variable POSIXLY_CORRECT is set, then option processing stops as soon as a nonoption argument is encountered.
I'm not sure if SLES11 sets POSIXLY_CORRECT by default. What is the best way to get the old SLES10 getopt behaviour in SLES11?
回答1:
It turns out that by default it was redirecting to _posix_getopt(), which was causing the behaviour I described above.
The possible solutions I found to this in the end:
- Use getopt_long() instead. This doesn't seem to have a posix equivalent.
- Define _GNU_SOURCE, which stops the redirection.
- Manually reorder the parameters, possibly using a wrapper shell script.
来源:https://stackoverflow.com/questions/13290788/how-to-allow-non-option-arguments-in-any-order-to-getopt