如何在做其他事情的同时从键盘获取输入?
我正在使用 C (gcc) 和 ncurses 来制作一个程序来监视来自串行端口的数据。该程序有一个很大的 while ,它读取来自端口的数据,同时在屏幕上打印该信息......
但问题在于:
它如何读取输入从我的键盘(因为 getch()
冻结程序直到获得输入)并同时读取来自端口的信息?
也许我必须使用另一种方式(不是大的while
),所以欢迎提出想法!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用 nodelay 选项使 getch 成为非阻塞调用。
更多信息请访问 http://www.gsp.com/cgi -bin/man.cgi?topic=nodelay
make getch a non-blocking call using nodelay option.
More info can be found at http://www.gsp.com/cgi-bin/man.cgi?topic=nodelay
根据您的环境,您可能拥有函数 kbhit(),它只是在键盘缓冲区中达到峰值,如果那里有键则返回非零 - 然后您可以执行 getch()。
(conio.h)
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)
也许 fork() ?请记住,子进程在单独的进程中运行,因此变量不能在它们之间直接共享
Maybe fork()? Just keep in mind that the child runs in a separate process so variables can't be directly shared between them
尝试
select()
或poll()
。它们都做同样的事情,但具有不同的接口。您给它一个文件描述符列表,它会等待至少一个描述符准备就绪,然后返回并告诉您可以在不阻塞的情况下读取(或写入)哪些描述符。查看链接以获取示例和更多详细信息。Try
select()
orpoll()
. 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.使用 cbreak() 禁用行缓冲,
这将为您提供非阻塞的 getch() 函数。
use
cbreak()
to disable line bufferingthis will get you a non blocking
getch()
function.