socket()在std :: thread中返回文件描述符1

wal*_*sht 3 sockets multithreading c++11

当我socket()在里面调用std::thread()它时,它返回一个套接字描述符1.调用而std::cout不是将终端文本发送到服务器.当我cout << "";在调用之前添加时socket(),将创建stdin/out/err for的描述符并socket()返回3.

来自http://www.cplusplus.com/reference/iostream/cout/:

在静态初始化顺序方面,cout保证在不晚于第一次ios_base::Init构造类型对象的情况下正确构造和初始化,其中包括<iostream>计数作为具有静态持续时间的这种对象的至少一个初始化.

默认情况下,coutstdout(参见ios_base::sync_with_stdio)同步.

std::cout应该已经初始化并同步到stdout,这解释了为什么要将std::cout消息发送到服务器而不是终端.

我想知道调用是否std::thread()关闭新线程中的stdin/out/err描述符,或者线程中是否存在这些描述符,因为该线程不是由终端或initd创建的?

我使用GCC 4.8.2在RHEL 6.4上运行.我已经在下面添加了我的客户端代码,并附加了cout << "";注释以确保完整性.

Client.cpp:

#include "Client.hpp"

#include <cstdlib>
#include <cstring>
#include <iostream>
#include <thread>
#include <vector>
#include <algorithm>
#include <sstream>
#include <functional>

#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>

using namespace std;

Client::Client( const string& hostname, const string& port ) {
    this->hostname = hostname;
    this->port = port;
}

Client::~Client() { close( fd ); }

void Client::operator()() {
    struct addrinfo hints;
    memset( &hints, 0, sizeof( struct addrinfo ) );

    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = 0;
    hints.ai_protocol = 0;

    struct addrinfo *result;
    int ret = getaddrinfo( hostname.c_str(), port.c_str(), &hints, &result );
    if( ret != 0) {
        cerr << "getaddrinfo failed: " << gai_strerror( ret ) << endl;
        return;
    }

    // cout << ""; // prevents socket() from returning 1 and redefining cout

    struct addrinfo *rp = NULL;
    for( rp = result; rp != NULL; rp = rp->ai_next ) {
        fd = socket( rp->ai_family, rp->ai_socktype, rp->ai_protocol );
        if( fd == -1 ) {
            continue;   /* Error */
        }

        if( connect( fd, rp->ai_addr, rp->ai_addrlen ) != -1) {
            break;      /* Success */
        }

        close( fd );        /* Try again */
    }

    if( rp == NULL ) {
        cerr << "Failed to connect to " << hostname << ":" << port << endl;
        return;
    }

    freeaddrinfo( result );

    cout << "Starting echo client" << endl;

    int i = 0;
    do {
        stringstream ss;
        ss << "Thread " << this_thread::get_id() << ": Message #" << ++i;
        string str = ss.str();

        _send( str.c_str() );
        string msg = _recv();

        //cout << "Thread " << this_thread::get_id() << " received message: " << msg << endl;
    } while ( i < 10 );

    cout << "Stopping echo client" << endl;

    close( fd );
}

string Client::_recv( ) const {
    const int BUF_SIZE = 1024;
    char* buf = ( char * ) malloc( sizeof( char) * BUF_SIZE );
    memset( buf, '\0', sizeof( char ) * BUF_SIZE );

    int bytes = recv( fd, buf, BUF_SIZE, 0 );
    if( bytes < 0 ) {
        perror( "recv failed" );
    }

    string msg = string( buf );

    free( buf );

    return msg;
}

void Client::_send( const string buf ) const {
    if( send( fd, buf.c_str(), buf.length(), 0 ) < 0 ) {
        perror( "send failed" );
    }
}
void usage() {
    cerr << "Usage: client <hostname> <port>" << endl;
    cerr << "   hostname - server name listening for incoming connctions" << endl;
    cerr << "   port - internet port to listen for connections from" << endl;
}

int main( int argc, char* argv[] ) {
    if( argc < 3 ) {
        cerr << "Not enough arguments!" << endl;
        usage();
        return EXIT_FAILURE;
    }

    vector<thread> clients;
    for( int i = 0; i < 1; i++ ) {
        clients.push_back( thread( ( Client( argv[1], argv[2] ) ) ) );
    }

    for_each( clients.begin(), clients.end(), mem_fn( &thread::join ) );

    return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)

Client.hpp:

#ifndef __CLIENT_HPP__
#define __CLIENT_HPP__

#include <string>

class Client {
    private:
        int fd;
        std::string hostname;
        std::string port;
        std::string _recv( ) const;
        void _send( const std::string buf ) const;

    public:
        Client( const std::string& hostname, const std::string& port);
        ~Client();
        void operator()();
};

#endif
Run Code Online (Sandbox Code Playgroud)

abl*_*igh 5

如果你不小心关闭了你stdout,通常会发生这种情况,即存在虚假的情况close(1);.那么FD将合法地为1号.这可能是该计划的其他地方.

我已经好几次了,通常会找到gdb并设置一个断点close().

你的析构函数看起来很可疑:

Client::~Client() { close( fd ); }
Run Code Online (Sandbox Code Playgroud)

你不应该被设定fd-1在构造函数中,精心设置fd-1任何你要关闭它,不这样做,如果接近fd==-1?目前创建Client并销毁它将关闭随机fd.