Take the 2-minute tour ×

I have a function that returns the strength of my Wifi signal on a certain interval.

FILE *sig;
int sigstr=0, max;
sig = popen("iwconfig wlan0 | awk '/Link/ {print $2}'","r");
fscanf(sig,"%d/%d", &sigstr, &max);

The problem I am running into is that my program freezes up after a period of time depending on how long the interval is for getting the Wifi signal. The shorter the interval the faster my program freezes. Now correct me if I am wrong but this seems to be a problem with memory. Where as time progresses some item(s) are not properly removed from the stack or deallocated, leading to memory being filled up and eventually reaching a level where the program can not continue to run. So my question is apart from what I have up top do I need to include another statement to free file sig or does pclose take care of that?


share|improve this question
sig is just a pointer. It takes 4 or 8 bytes of memory depending on the architecture. It is not taking up nearly enough space. My bet is that fscanf is returning and error. Grab the return value and check errno. –  Magn3s1um Jul 10 '13 at 17:15
If the subprocess fails to produce the expected output for whatever reason, your while(fgetc(sig)!='='); will loop forever. –  Casey Jul 10 '13 at 17:16
add comment

1 Answer

Its because fscanf can block. Set your file descriptor obtained from popen to nonblocking using fcntl.

share|improve this answer
Thanks for the response! Is this the proper way to set nonblocking? 'fcntl(fileno(sig), F_SETFL, O_NONBLOCK);' I am getting "awk: close failed on file /dev/stdout (Broken pipe)" as an error when I run it. –  hein13 Jul 10 '13 at 18:00
Yep, thats it. Make sure you flush the buffer before you try closing by doing an fsync or flush. –  Magn3s1um Jul 10 '13 at 18:03
I am having a problem now fscanf returns -1 and sets errno to EAGAIN. –  hein13 Jul 10 '13 at 18:32
I know on android, if you keep calling the scan function, it will timeout because you have to wait for the device to finish. You might have to set a sleep timer on it so that you don't overflow its instruction buffer. –  Magn3s1um Jul 10 '13 at 19:04
add comment

Your Answer


