我有一个服务器,它为每个客户端创建一个线程。这是线程函数,我的程序在那里等待发送数据。如果没有数据在5秒内发送,我需要以某种方式关闭此线程。我尝试使用该信号/报警组合,并以某种方式工作,但其余的线程功能正在继续打印错误,因为sClient(套接字)已关闭。我怎样才能完成这项工作,或者可能是其他解决方案?
void time_out() {
char r = "-1";
printf("Time out");
send(sClient, &r, 10, 0);
close(sClient);
}
void* thread(void *arg) {
sClient = (int)arg;
int size;
char* buffer = (char*)malloc(300);
signal(SIGALRM, time_out);
alarm(5);
if (recv(sClient, (char*)&size, sizeof(int), 0) < 0) {
printf("Error when getting length \n");
}
....
}
答案 0 :(得分:3)
听起来你应该打开线程,等待5秒钟,然后检查sClient的数据。如果没有数据,则可以立即关闭该线程。否则,如果有数据,您可以调用recv来实际获取数据。
为此,您可以使用select
调用超时来检查套接字上的新数据。
(有关超时的select
如何工作,请参阅“socket timeout: It works, but why and how, mainly the select() function?”。)