How to get input from keyboard while doing other t

2019-02-12 12:38发布

问题:

I'm using C (gcc) and ncurses, to make a program that will be monitoring data coming from the serial port. The program has a big while, where it reads the data coming from the port and at the same time, it prints that info in the screen...

But the problem is here:

How can it read input from my keyboard, (since getch() freezes the program until it gets an input) and at the same time read info coming from the port?

Maybe I have to use another way (not the big while), so ideas are welcome!

回答1:

make getch a non-blocking call using nodelay option.

nodelay(stdscr,TRUE);

More info can be found at http://www.gsp.com/cgi-bin/man.cgi?topic=nodelay



回答2:

Depending on your environment you maybe have the function kbhit(), it just peaks in the keyboard buffer and returns non zero if there is a key there - then you can do getch().

(conio.h)



回答3:

Maybe fork()? Just keep in mind that the child runs in a separate process so variables can't be directly shared between them

pid_t pID = fork();
if (pID == 0) {                // child
   // Code  executed only by child process
   // getch() ...
} else if (pID < 0) {          // failed to fork
   // Throw exception
   // ... 
} else {                       // parent
   // Code executed only by parent process
   // ...
}


回答4:

Try select() or poll(). They both do the same thing, but with different interfaces. You give it a list of file descriptors, and it will wait until at least one of those descriptors is ready, then return and tell you which ones can be read from (or written to) without blocking. Check out the links for examples and more details.



回答5:

use cbreak() to disable line buffering

nodelay(win, TRUE); 

this will get you a non blocking getch() function.



标签: c ncurses