socket select()创建一个线程,close()不结束线程

时间:2013-10-02 13:40:18

标签: c++ sockets cygwin

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

我在cygwin中运行代码。在第一次暂停时我附加gdb并且有三个线程(不知道为什么三个)。我退出gdb并继续打开的程序执行以下操作:打开socket,bind,select,close。然后我点击第二个暂停,然后附加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;
}

1 个答案:

答案 0 :(得分:0)

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