c - 读取循环内的停止信号

标签 c unix

我正在使用一个不会终止的 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/

相关文章:

c - 为什么 pushl %ebp 和 movl %esp, %ebp 在每个 ASM 函数的开头?

c - gcc makefile 无法编译

c - 网络字节序遍历结构体(Big Endian) --- C语言

c - 当我运行它时,此代码不执行任何操作。为什么?

perl - 使用 Net :SSH:Perl module 时的协议(protocol)错误

使用系统调用将一个文件的内容复制到另一个文件

c - C 中 *ptr 和 ptr* 有什么区别?

objective-c - Objective-C 中的 NSBundle 沙箱

shell - 检查PID是否僵化的可移植shell解决方案

ruby - 在 smartos plus 上安装 ruby