Last active
August 29, 2015 14:14
-
-
Save ymmt2005/7c0ca977be998b52edc3 to your computer and use it in GitHub Desktop.
shutdown and recv
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// g++ -std=gnu++11 hoge.cpp -lpthread | |
#include <cerrno> | |
#include <chrono> | |
#include <cstring> | |
#include <iostream> | |
#include <netdb.h> | |
#include <sys/socket.h> | |
#include <sys/types.h> | |
#include <system_error> | |
#include <thread> | |
using namespace std; | |
void recv_thread(int fd) { | |
char buf[100]; | |
while( true ) { | |
ssize_t r = ::recv(fd, buf, sizeof(buf), 0); | |
cerr << "recv returns " << r << endl; | |
if( r == 0 ) | |
break; | |
if( r == -1 ) { | |
error_code e{errno, std::system_category()}; | |
cerr << "recv: " << e << endl; | |
break; | |
} | |
} | |
} | |
int main(int argc, char** argv) { | |
if( argc != 3 ) { | |
cerr << "Usage: hoge HOST PORT" << endl; | |
return 0; | |
} | |
struct addrinfo hints, *r; | |
memset(&hints, 0, sizeof(hints)); | |
hints.ai_family = AF_INET; | |
hints.ai_socktype = SOCK_STREAM; | |
hints.ai_flags = 0; | |
hints.ai_protocol = 0; | |
int e = getaddrinfo(argv[1], argv[2], &hints, &r); | |
if( e != 0 ) { | |
cerr << "getaddrinfo: " << gai_strerror(e) << endl; | |
return 1; | |
} | |
if( r == nullptr ) { | |
cerr << "getaddrinfo: No result" << endl; | |
return 1; | |
} | |
int s = ::socket(r->ai_family, r->ai_socktype, r->ai_protocol); | |
e = ::connect(s, r->ai_addr, r->ai_addrlen); | |
freeaddrinfo(r); | |
if( e != 0 ) { | |
error_code e{errno, std::system_category()}; | |
cerr << "connect: " << e << endl; | |
return 1; | |
} | |
thread t1(recv_thread, s); | |
cerr << "start recv thread ..." << endl; | |
this_thread::sleep_for( chrono::seconds{1} ); | |
cerr << "shutdown socket ..." << endl; | |
::shutdown(s, SHUT_RD); | |
cerr << "joining ..." << endl; | |
t1.join(); | |
cerr << "done." << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment