我有这个:
#define STDIN 0
char buffer[512];
bzero(buffer,512);
struct sockaddr_in from;
string input;
RoutingMessage parser;
cout << "Listening...\n";
/* Temporary fix.
/* This should be abstracted, and more widely used
/********* Start Select() ***********/
fd_set readfds;
struct timeval tv;
tv.tv_sec = 120;
tv.tv_usec = 0; //wait for 1.5 second here
int rv = 1;
// clear the set ahead of time
FD_ZERO(&readfds);
// add our descriptors to the set
FD_SET(mySocket, &readfds);
FD_SET(STDIN, &readfds);
// the n param for select()
int n = mySocket + 1;
/********* End Select() ***********/
while(rv != 0)
{
rv = select(n, &readfds, NULL, NULL, &tv);
if (rv == -1)
perror("select"); // error occurred in select()
if (FD_ISSET(STDIN, &readfds))
{
cin >> input;
cout << input << endl;
}
else
{
bzero(buffer,512);
int n = recvfrom(mySocket,buffer,512,0,(struct sockaddr *)&from, &sockLen);
if (n < 0)
perror("recvfrom");
if (n > 0)
{
parser.ParseMessage(buffer, fromNode, messages);
ProcessMessages();
}
}
}
然而,当我尝试在程序中输入任何内容时,我没有得到cout的响应:
Listening...
3702 has converged!
3701 has converged!
3703 has converged!
test
// blank line
我做错了吗?
答案 0 :(得分:3)
选择更改传入的readfds
。每次调用select时,您都必须提供要监视事件的文件描述符。 e.g。
while(rv != 0) {
FD_ZERO(&readfds);
FD_SET(mySocket, &readfds);
FD_SET(STDIN, &readfds);
rv = select(n, &readfds, NULL, NULL, &tv);