从控制台读取输入,无需无条件等待(非等待扫描)



我正在尝试编写代码以连续从控制台读取输入并更新应用程序中的变量。但是,如果我们使用 scanf 函数,每当函数命中时,它都会期望用户通过控制台输入,并且只有在收到来自控制台的输入时才继续进一步的指令,否则它会无条件等待。

我的代码是这样的

int x, y;
while(1)
{
scanf("%d", &x);
y = x;
----
----
//Remaining code for execution
}

我的期望是应用程序不应该等待来自控制台的输入。如果用户在控制台中输入某些输入,则应读取并使用该输入,否则即使未输入,应用程序也应执行剩余指令或应使用旧值。有没有其他方法可以在不使用scanf的情况下编写这样的代码?谢谢!

您可以选择((/epoll(( 函数进行输入,如果发生超时,它将继续进行。 由于 stdin 也是一个 FD,您可以注册比 FD 选择在给定的 FD 上工作。

请参考 : https://stackoverflow.com/a/21198059/6686352

您可以使用超时为零(非 NULL(的select()来检查数据是否可用,然后才调用 scanf。

示例(没有正确的错误处理(:

#include <stdio.h>
#include <unistd.h>
#include <sys/select.h>
int main()
{
int x;
fd_set fds;
struct timeval tv = { .tv_sec = 0, .tv_usec = 0 };
while (1) {
FD_ZERO(&fds);
FD_SET(0, &fds);  // Watch stdin (fd 0)
if (select(1, &fds, NULL, NULL, &tv)) {
scanf("%d", &x);
printf("Got %d from stdin", x);
}
printf("Working..n");
sleep(1);
}
}

您可以使用fcntl将 stdin 设置为非阻塞。这使得scanf提前返回,否则它会阻止EAGAIN

示例(没有正确的错误处理(:

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
int main()
{
int x;
fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
while (1) {
int ret = scanf("%d", &x);
if (ret > 0)
printf("Got %d from stdin", x);
printf("Working..n");
sleep(1);
}
}

最新更新