我正在尝试使用以下程序从文件描述符“0”(STDIN)中读取用户输入。以前,它没有问题,但是在程序的其他部分进行了一些更改之后,它在读取输入时给了我一个分段错误。我还删除了“FD_CLR(0, &readfds)”以查看它是否有效,但它没有。你能检查一下问题出在哪里吗?
char *userInput;
FD_ZERO(&masterfds);
FD_SET(0, &masterfds);
FD_SET(udp_con, &masterfds);
maxfds = udp_con;
while(exit == false)
{
readfds = masterfds;
selectFunc = select(maxfds+1, &readfds, NULL, NULL, &tv);
if(selectFunc < 0)
{
message("error in select");
exit = true;
}
else if(selectFunc == 0) //If there is a timeout
{
}
else //If a file descriptor is activated
{
if(FD_ISSET(udp_con, &readfds)) //If there is an activity on udp_con
{
/*read the udp_con via recvfrom function */
}
if(FD_ISSET(0, &readfds)) //If There is an input from keyboard
{
/* When it reaches to this part, the program shows a "segmentation fault" error */
fgets(userInput, sizeof(userInput), stdin);
int len = strlen(userInput) - 1;
if (userInput[len] == '\n')
{
userInput[len] = '\0';
}
string str = userInput;
cout<<"The user said: "<<str<<endl;
commandDetector(str);
FD_CLR(0, &readfds);
}
}
}