如何中断阻塞方式accept调用
鲫鱼跃龙门 2008-10-23 03:50:27 测试代码如下:
int sock = -1;
void *thlsn(void *param)
{
int newsock = 0;
struct sockaddr addr;
socklen_t len;
printf("start to accept\n");
newsock = accept(sock, &addr, &len);
printf("accept returned\n");
return NULL;
}
int main()
{
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0)
{
perror("socket");
}
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(12345);
addr.sin_addr.s_addr = INADDR_ANY;
if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)))
{
perror("bind");
}
if (listen(sock, 2))
{
perror("listen");
}
pthread_t th = 0;
if (pthread_create(&th, NULL, thlsn, NULL))
{
perror("pthread_create");
}
sleep(5);
close(sock);
sock = -1;
pthread_join(th, NULL);
return 0;
}
运行后立刻输出:start to accept
五秒过后,accept依然阻塞,谁知道要如何让其返回?