1

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

我在 cygwin 中运行代码。在第一次暂停时,我附加了 gdb,并且有三个线程(不知道为什么是三个)。我退出 gdb 并继续打开的程序执行以下操作:打开套接字、绑定、选择、关闭。然后我点击第二次暂停,然后附加 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;
}
4

1 回答 1

0

关闭 UDP 套接字根本不会导致对该套接字的选择结束。我不清楚为什么,但这是预期的行为。看到这个老问题

于 2013-10-02T13:50:24.927 回答