How to allow non-option arguments in any order to getopt?

a 夏天 提交于 2019-12-10 15:36:56

问题


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:

  1. Use getopt_long() instead. This doesn't seem to have a posix equivalent.
  2. Define _GNU_SOURCE, which stops the redirection.
  3. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!