Linux C ++ boost asio,如何正确停止侦听端口

时间:2016-10-06 18:20:17

标签: c++ linux boost boost-asio

我编写了一个简单的代码来演示我的boost tcp服务器的问题。问题是,如果应用程序已经有子进程,我无法停止然后再次绑定到同一个端口,即使父进程关闭接受者,它(子)也继续侦听端口。

#include <iostream>
#include <chrono>
#include <thread>
#include <boost/asio.hpp>
#include <boost/bind.hpp>

using namespace std;

void handle_accept(boost::asio::ip::tcp::socket *sock, const boost::system::error_code & err)
 {
    if ( err) {
        cerr << "Err" << endl;
        return;
    }
}

int main() {

    boost::asio::io_service service;
    boost::asio::ip::tcp::endpoint ep( boost::asio::ip::address_v4::loopback(), 8080);
    boost::asio::ip::tcp::acceptor tcp_acceptor_(service);
    tcp_acceptor_.open(ep.protocol());
    tcp_acceptor_.bind(ep);
    tcp_acceptor_.listen();

    boost::asio::ip::tcp::socket socket(service);
    tcp_acceptor_.async_accept(socket, boost::bind( handle_accept, &socket, _1) );

    cout << "Acceptor started" << endl;

    system("sleep 600 &");
    std::this_thread::sleep_for(std::chrono::seconds(10));

    cout << "Close acceptor" << endl;

    tcp_acceptor_.close(); 

    std::this_thread::sleep_for(std::chrono::seconds(100));
    return 0;
}

程序启动时netstat显示我的程序监听端口8080:

~/tmp/tcp_server$ netstat -tanp | grep 8080
(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)
tcp        0      0 127.0.0.1:8080          0.0.0.0:*               LISTEN      22340/a.out  

致电后

tcp_acceptor_.close();

netstat显示子程序“sleep”继续侦听端口8080

~/tmp/tcp_server$ netstat -tanp | grep 8080
(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)
tcp        0      0 127.0.0.1:8080          0.0.0.0:*               LISTEN      22342/sleep 

因此,在“睡眠”退出之前,我无法开始监听端口8080。 我知道子进程继承了开放的套接字,但如果它有子进程,如何在程序中正确启动/停止/启动侦听端口?

0 个答案:

没有答案