c++ - 程序在 accept() 之后终止启动线程

标签 c++ linux sockets

所以我正在尝试构建一个服务器,它接受套接字上的连接,然后围绕执行一个函数创建一个线程,该函数使用接受的连接的新打开的文件描述符。我遇到的问题是,当我启动线程时,服务器返回接受另一个连接(如果有的话)但它不会阻塞?它似乎正在从循环中返回,我不知道为什么要这样做。正在运行的代码是:

listen(sockfd,10);
int i = 0;
for(;;)
{
    std::cout << "Before accept" << endl;
    clilen = sizeof(cli_addr);
    newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
    std::cout << "After accept" << endl;

    if (newsockfd < 0)
    {
        std::cout << newsockfd << ": Error on accept" << endl;
        continue;
    }
    else
        std::cout << newsockfd << ": Connection accepted!" << endl;

    boost::thread(boost::bind(&Class::FunctionToRun, this, newsockfd)).start_thread();
    std::cout << ++i << endl;
}

脚趾控制台的输出是:

Socket opened! fd = 3
Before accept
After accept
4: Connection accepted!
1
Before accept
[program terminates]

但是如果 accept 在等待套接字上的新连接时阻塞,那么程序怎么会在打印“After accept”之前终止呢?

最佳答案

问题是你在没有加入它的情况下立即销毁了你的线程:

    boost::thread(boost::bind(&Class::FunctionToRun, this, newsockfd)).start_thread();
    // already dead here
    std::cout << ++i << endl;
}

如果你想让你的线程四处闲逛,你需要将它们存储在某个地方:

std::vector<std::unique_ptr<boost::thread>> threads;
for (;;) {
    // ...
    threads.emplace_back(new boost::thread(boost::bind(...)));
    // thread is still alive here
    std::cout << ++i << endl;
}

如果不是 C++11,那么您可以将其设为 vector<boost::shared_ptr<boost::thread>>完成同样的事情。

关于c++ - 程序在 accept() 之后终止启动线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27049209/

相关文章:

java - LoadLibrary 仅在从 eclipse 和 tomcat 运行时失败

C++ 同时写入 std::out 和 std:clog

c++ - #ifdef 不接受枚举定义

linux - 使用 Ansible 获取 Linux 网络接口(interface)名称?

linux - iptables 端口转发 - 没有返回任何内容

c - 如何区分同一套接字上的读写事件?

javascript - 使用socket.io与 react 问题

ajax - 是否可以将 socket.io 客户端与自定义 C# Web 服务器一起使用?

c++ - qhull 库 - C++ 接口(interface)

c++ - 我是否需要为指向构造函数的 char 指针分配内存?