如何使用select从stdin读取输入? [英] How to use select to read input from stdin?

查看:334
本文介绍了如何使用select从stdin读取输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用selectstdin读取数据,之后我通过套接字将数据发送到服务器.

I am trying to read from stdin using select, after that I am sending the data through a socket to a server.

以下代码段应遵循上述逻辑;但它不会从stdin读取任何内容.

The following snippet is supposed to follow the above logic; but it doesn't read anything from stdin.

此外,它在用户第一次输入字符串后打印Enter command:. printf("%d %s\n",__LINE__ ,buf);行也不显示任何内容.

Moreover it prints Enter command: after the first time the user inputs a string. The line printf("%d %s\n",__LINE__ ,buf); doesn't print anything as either.

fd_set rfds;
struct timeval tv;
int retval; 
char buf[BUFLEN];
while(1) {
    FD_ZERO(&rfds);
    FD_SET(STDIN_FILENO, &rfds);
    tv.tv_sec = 5;
    tv.tv_usec = 0;
    retval = select(STDIN_FILENO + 1, &rfds, NULL, NULL, &tv);
    if (FD_ISSET(STDIN_FILENO, &rfds)) {
        if (fgets(buf,BUFLEN, stdin)) {
              printf("%d %s\n",__LINE__ ,buf);
          if (strncmp(buf, "exit", 4) == 0)
                exit(0);
         }
         printf("\nEnter command: ");
    }
}

为什么我只能连续打印Enter command:?

why do I get only Enter command: printed endlessly ?

问题出在我使用的嵌入式设备上,并通过-fpic进行了某种编译,从而解决了该问题.

the problem was with the embedded device I was using and somehow compile it with -fpic fixed the problem.

推荐答案

尝试

FD_ZERO(&rfds);
FD_SET(STDIN_FILENO, &rfds);

在while循环内

这篇关于如何使用select从stdin读取输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆