How to get input from keyboard while doing other things at the same time?

烂漫一生 提交于 2019-11-30 02:58:36

问题


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.



来源:https://stackoverflow.com/questions/3939888/how-to-get-input-from-keyboard-while-doing-other-things-at-the-same-time

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!