I have read the writing on the wall, Avoid Globals. Which leads to the obvious question, how best to do it?
I obviously want to do it with a current project. The goal is to let a distant PC send "keystrokes" to applications that already have an stdin reader. The idea is to let the existing code detect there is no pending keystroke, then check if there is a "udp keystroke" and, if so, stuff it in so it appears to be keyboard input. Minimally invasive and won't require gobs of retro-fitting in other people's code.
So I cobbled up a small UDP socket reader that uses a setup()
function to open and bind the port, then a service()
function in a loop that uses a nonblocking select()
once, no loop, just check if there is anything to read right now. If so, read the data from the socket and do something with it, else return a 0.
// pseudo c
char c;
setup();
while (1)
{
c = check_for_keyboard_entry();
if ( c == 0 )
c = service();
handle_keypress( c );
do_a_bunch_of_other_stuff();
}
The obvious way to do this is with a few globals to transfer the port, timeout, sockaddr's etc. between the two functions. But, thou shalt avid globals, right?
So what is a preferred way to transfer the six or eight vars between the functions?
If I were to use static vars in the setup()
, would they be accessible by the service()
routine?
I suppose a struct that gets malloc-ed and passed around would work. I'd ought to have a cleanup()
to close the socket and free the memory.
REMEMBER, THIS IS A C QUESTION. NO C++!