Page 1 of 1

getopt() alert

Posted: Fri Feb 15, 2013 10:36 pm
by pconroy328
Others have discovered that getopt() on the pi acts a little differently from what you have likely used in the past. Examples of getopt() usage will show something similar to this:

Code: Select all

while (((c = getopt (argc, argv, "hb:f:s:jvcCr")) != -1))
What you need to do is add a check for 255 too:

Code: Select all

while (((c = getopt (argc, argv, "hb:f:s:jvcCr")) != -1) && (c != 255))
This one difference caused me a few extra minutes of debugging. Thanks to this site for the help: http://forum.gadgetfactory.net/index.ph ... -pi-ideas/

Re: getopt() alert

Posted: Fri Feb 15, 2013 11:11 pm
by xian
Thant you for the heads up, I'd be interested to know how this came about.

Re: getopt() alert

Posted: Sat Feb 16, 2013 12:13 am
by bgreat
For your example, do you have "c" declared as "int"? I've only seen the problem you describe when "c" is declared "unsigned char". Can we see more of your test code?

Enjoy!
Bill

Re: getopt() alert

Posted: Sat Feb 16, 2013 12:48 am
by technion
I've checked several standard application and they seem to use getopt() without having the issue you listed.

As posted, can we see more of your code?

getopt() returns an int. If you cast that to an unsigned char, -1 will become 255.

Re: getopt() alert

Posted: Sat Feb 16, 2013 2:55 am
by jojopi
On ARM Linux, plain "char" is an unsigned type. Which is perfectly legal in C, so the code that expects it to hold -1 is buggy.

You can either fix the bug, or compile with "gcc -fsigned-char".

Re: getopt() alert

Posted: Sat Feb 16, 2013 3:55 pm
by pconroy328
Yep - I know folks. My point was if you Google "getopt example", you're going to get pointed to the incorrect code. Which behaves as you'd expect it to on an x86 Linux machine. It behaves as you'd not expect it to on the Pi.

The example's clearly wrong. I just didn't notice it until I started porting some code.
It was simply a "Heads Up!" post. :D

Re: getopt() alert

Posted: Sat Feb 16, 2013 6:39 pm
pconroy328 wrote:Yep - I know folks. My point was if you Google "getopt example", you're going to get pointed to the incorrect code. Which behaves as you'd expect it to on an x86 Linux machine. It behaves as you'd not expect it to on the Pi.

The example's clearly wrong. I just didn't notice it until I started porting some code.
It was simply a "Heads Up!" post. :D
I use getopt() on the Pi.

I have just googled "getopt example". The first hit shows me:

Code: Select all

      int c;
     
       opterr = 0;
     
       while ((c = getopt (argc, argv, "abc:")) != -1)
Which works just fine.

c is an int. The full example on that page, works as intended.

From the man page: man 3 getopt:

Code: Select all

       #include <unistd.h>

       int getopt(int argc, char * const argv[],
                  const char *optstring);

I think you (or the code you're porting) defined c as a char, not an int.

-Gordon