我正在使用一个不会终止的 while 循环,用于使用 C 代码重现 unix 的 Tail 命令。我需要一种方法来停止循环,除了 Ctrl + C 之外,它会退出我认为的进程。在代码中使用时有什么方法可以读取键盘命令吗?使用 getchar() 的问题是它会停止循环运行,直到输入一个字符。这个问题有其他解决方案吗?
最佳答案
您需要关闭阻塞和行缓冲。关闭阻塞,以便 getc()
立即返回。它将返回-1,直到它具有真实的字符。关闭行缓冲,以便操作系统立即发送字符,而不是缓冲它,直到它有一个完整的行(当您按回车键时发生)。
#include <unistd.h> /* UNIX standard function definitions */
#include <fcntl.h> /* File control definitions */
#include <termios.h> /* POSIX terminal control definitions */
int main(void) {
// Turn off blocking
fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK);
struct termios options, oldoptions;
tcgetattr(STDIN_FILENO, &options);
// Disable line buffering
options.c_lflag &= ~( ICANON);
// Set the new options for the port...
tcsetattr(STDIN_FILENO, TCSANOW, &options);
while(1) {
char c = getc(stdin);
if(c != -1) break;
}
// Make sure you restore the options otherwise you terminal will be messed up when you exit
tcsetattr(STDIN_FILENO, TCSANOW, &oldoptions);
return 0;
}
我同意其他发帖者的观点,即您应该使用信号
,但这就是您所问问题的答案。
关于c - 读取循环内的停止信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12526483/