Perhaps someone can pick up on something I missed on a few cursory passes, but I would try to narrow down the scope of the problem a bit further. You said you sprinkled some debugging code all around to identify its progress through the loop. Were you able to nail it down to a specific spot that was blocking/looping? Were you able to identify a function or other call that was blocking and not returning control? If you're not getting responsive debugging output, be sure
is set to 1, so that stdio buffering isn't keeping you from seeing something when you should be.