gpt4 book ai didi

c++ - socket select() 创建一个线程并且 close() 不结束线程

转载 作者:太空宇宙 更新时间:2023-11-04 14:01:32 27 4
gpt4 key购买 nike

当我在套接字上执行选择时,它会创建一个线程。当我关闭套接字时,它不会释放线程。

我在 cygwin 中运行代码。在第一次暂停时,我附加了 gdb,并且有三个线程(不确定为什么是三个)。我退出 gdb 并继续打开的程序执行以下操作:打开套接字、绑定(bind)、选择、关闭。然后我打了第二次暂停,然后附加 gdb,现在有四个线程。我什至添加了关机。我确信我遗漏了一些简单的东西,但我似乎找不到它。

这是代码。

#include <netdb.h>
#include <fstream>
#include <iostream>

#include <shlobj.h>

using namespace std;

void mySleep(int miliSeconds)
{
usleep(miliSeconds * 1000);
}

void mySleep(int miliSeconds)
{
// Sleep(miliSeconds);
usleep(miliSeconds * 1000);
}


void myPause()
{
cout << "Paused, hit enter to continue..."<< endl;

getchar();
}


int main()
{
myPause();
struct sockaddr_in serv_addr, client_addr;

client_addr.sin_family = AF_INET;
client_addr.sin_port = htons(10000);
client_addr.sin_addr.s_addr = htonl(INADDR_ANY);

struct hostent* server = gethostbyname("127.0.0.1");
memset((char *) &serv_addr, 0, sizeof (serv_addr));
serv_addr.sin_family = AF_INET;
memcpy((char *)&serv_addr.sin_addr.s_addr, (char *) server->h_addr, server->h_length);
serv_addr.sin_port = htons(10000);

int sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sockfd < 0)
{
cout << "Error opening socket" << endl;
exit(-1);
}

int retCode;
socklen_t sockAddrLen = sizeof(sockaddr_in);

retCode = bind(sockfd, (const struct sockaddr *) &client_addr, sockAddrLen);
if (retCode < 0)
{
cout << "Unable to bind" << endl;
close(sockfd);
exit(-1);
}
struct timeval tv;
fd_set socks;

FD_ZERO(&socks);
FD_SET(sockfd, &socks);

tv.tv_sec = 5;
tv.tv_usec = 0;
retCode = select(sockfd + 1, &socks, NULL, NULL, &tv);
if (retCode < 0)
{
cout << "Unable to select" << endl;
close(sockfd);
exit(-1);
}

retCode = shutdown(sockfd, 2); // 2 = stop both reception and transmission
if (retCode < 0)
{
cout << "Unable to shutdown" << endl;
close(sockfd);
exit(-1);
}
retCode = close(sockfd);
if (retCode < 0)
{
cout << "Unable to close" << endl;
close(sockfd);
exit(-1);
}
sockfd = -1;

mySleep(5000);
myPause();

return 0;
}

最佳答案

关闭 UDP 套接字不会简单地导致对该套接字的选择结束。我不清楚为什么,但这是预期的行为。参见 this older question

关于c++ - socket select() 创建一个线程并且 close() 不结束线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19138295/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com