0

我正在编写这个使用 ncurses 作为界面的聊天程序。我想如何同时处理套接字文件描述符和用户交互?我的想法如下。现在的问题是循环只为我按下的每个按钮执行一次。如何构建我的程序,以便套接字和用户交互一旦准备好就立即处理?我试着让我的投票包括标准输入和输出的文件描述符,但这不起作用。

while(ch = getch()) {
   poll sockets
   loop sockets {
      ...
   }
   switch(ch) {
      ...
   }
} 

也作为一个更普遍的问题。通常如何编写程序来同时处理用户交互和其他事情?似乎会有一种标准的方法来做到这一点。

4

2 回答 2

1

nodelay()您可以在输入屏幕上尝试。

nodelay(stdscr,TRUE); // turn off getch() blocking

while(getch() == ERR)
{
    //do other stuff
}
else
    //handle input

但是你可能想要去线程化。

于 2012-02-20T18:27:25.270 回答
0

构建一个包含 STDIN 以及您尝试读取的套接字的文件描述符集 (FD_SET),然后在该集上使用 select()。类似于以下内容::

int main(int argc, char **argv)
{
  fd_set fds;
  int fd = open(/* your socket */);
  struct timeval tv;

  FD_ZERO(&fds);
  FD_SET(STDIN_FILENO, &fds);
  FD_SET(fd, &fds);

  while (1) {
     tv.tv_sec = 1; // wait for up to 1 sec
     int retval = select(2, &fds, NULL, NULL, &tv);
     if (retval > 0) {
        if (FD_ISSET(STDIN_FILENO, &fds)) 
            // process stdin
        else if (FD_ISSET(fd, &fds))
            // process data from your socket
     } else if (retval == 0) 
        // timeout
     else
        // some error
   }
   exit 0;
}

(注意我没有编译这个,但你应该明白了。)

请参阅fd_set选择教程

于 2012-02-20T23:07:41.083 回答