套接字连接过多后崩溃

时间:2018-09-28 09:32:29

标签: c++ linux sockets unix-socket

当客户端使用(Unix域)套接字连接到我的服务器时,一切似乎运行良好:建立连接,处理请求,客户端收到响应并且关闭连接。但是,经过一定数量的连接后,服务器将崩溃。我检查了连接循环,发现由套接字函数accept()(包装在app.newConnectionEstablished()中)返回的连接ID一直增加,直到达到1024的限制并且程序崩溃。

为什么连接ID不会总是重置为最低的可用数字?

#include <thread>
#include <mutex>
#include <condition_variable>
#include <deque>

#include "UdsServer.hpp"
#include "RequestManager.hpp"
#include "MSutils.hpp"


RequestManager service;


std::deque<std::string> requestQueue;
std::deque<int> connectionQueue;

std::mutex requestQueue_mutex;
std::condition_variable threadSwitch;

bool gotNewRequests = false;


void processRequest ()
{
    UnixDomainSocket uds;

    std::unique_lock<std::mutex> writeLock(requestQueue_mutex);

    while (true)
    {
        while (!gotNewRequests) 
            threadSwitch.wait(writeLock);

        auto currentRequest = requestQueue[0];
        auto currentConnection = connectionQueue[0];

        requestQueue.pop_front();
        connectionQueue.pop_front();

        gotNewRequests = false;

        writeLock.unlock();

        const std::string & response = service.processRequest(currentRequest);

        if (response.length())
        {
            auto ret = uds.sendMsg(currentConnection, response);

            if (!ret.isValid())
                MF::log("Could not send the response for request.");
        }

        uds.closeConnection(currentConnection);

        writeLock.lock();
    }
}


int main()
{
    UdsServer app;

    app.createServer("./App.sock");


    unsigned n_concThreads = 6;


    for (int i = 0; i < n_concThreads; ++i)
    {
        std::thread t (processRequest);
        t.detach();
    }

    int clientConnection = -1;

    while ((clientConnection = app.newConnectionEstablished()) > -1)
    {
        std::string command = app.getMsg (clientConnection);

        {
            std::unique_lock<std::mutex> writeLock(requestQueue_mutex);

            requestQueue.push_back(command);
            connectionQueue.push_back(clientConnection);
            gotNewRequests = true;
        } //Get rid of the lock before notifying the threads

        threadSwitch.notify_all(); //nothing happens here if all threads are busy
    }
}

这是打开和关闭连接的方式(显示连接的ID):

open 6
close 6
open 7
close 7
open 6
close 6
open 6
close 6
open 6
close 6
open 19
close 19
open 6
close 6
open 6
close 6
open 28
close 28
open 6
close 6
open 6
close 6
open 37
close 37
open 6
...

0 个答案:

没有答案