如何在“top”linux命令中进行控制台输入?

时间:2013-01-14 16:26:30

标签: c++ c linux input console

因此,linux top命令具有与控制台输出类似的实时循环(没有任何花哨的东西),但它使用非阻塞控制台输入,它不会在命令行中显示类型字符。怎么做的?有没有它的库,他们使用线程吗?我需要编写一个具有相同风格的linux应用程序(通过ssh使用),我不知道如何做这个输入(单独的线程中的cin不是解决方案,top使用其他东西)。

2 个答案:

答案 0 :(得分:7)

一种解决方案是使用curses的实现。

我不知道top是如何做到的。

答案 1 :(得分:3)

另一种选择,不使用curses:

#include <stdio.h>
//#include <unistd.h>
#include <termios.h>
//#include <sys/ioctl.h>
//#include <sys/time.h>
//#include <sys/types.h>
#include <fcntl.h>

//------------------------------------------------------------------------------
// getkey() returns the next char in the stdin buffer if available, otherwise
//          it returns -1 immediately.
//
int getkey(void)
{
    char ch;
    int error;
    struct termios oldAttr, newAttr;
    int oldFlags, newFlags;
    struct timeval tv;
    int fd = fileno(stdin);
    tcgetattr(fd, &oldAttr);
    newAttr = oldAttr;
    oldFlags = fcntl(fd, F_GETFL, 0);

    newAttr.c_iflag = 0; /* input mode */
    newAttr.c_oflag = 0; /* output mode */
    newAttr.c_lflag &= ~ICANON; /* line settings */
    newAttr.c_cc[VMIN] = 1; /* minimum chars to wait for */
    newAttr.c_cc[VTIME] = 1; /* minimum wait time */

    // Set stdin to nonblocking, noncanonical input
    fcntl(fd, F_SETFL, O_NONBLOCK);
    error=tcsetattr(fd, TCSANOW, &newAttr);

    tv.tv_sec = 0;
    tv.tv_usec = 10000; // small 0.01 msec delay
    select(1, NULL, NULL, NULL, &tv);

    if (error == 0)
        error=(read(fd, &ch, 1) != 1); // get char from stdin

    // Restore original settings
    error |= tcsetattr(fd, TCSANOW, &oldAttr);
    fcntl(fd, F_SETFL, oldFlags);

    return (error ? -1 : (int) ch);
}

int main()
{
    int c,n=0;
    printf("Hello, world!\nPress any key to exit. I'll wait for 4 keypresses.\n\n");
    while (n<4)
    {
        //printf("."); // uncomment this to print a dot on each loop iteration
        c = getkey();
        if (c >= 0)
        {
            printf("You pressed '%c'\n", c);
            ++n;
        }
    }
}

对不起,我不能完全相信这一点,因为我把它从多年前的网上拉下来了。我想我已经稍微调整了一下,但是从我得到它的地方来看它几乎没有变化。不幸的是,我没有添加评论,表明我找到了它。