Hi list,
I have trouble using g++'s stdio_filebuf extension with sockets.
I'm using gcc 3.4.1 on a Linux system.
Writing to a stdio_filebuf that is connected to a socket always fails,
leaving the stream in a bad state. See the following program for illustration:
#include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h>
#include <string> #include <iostream> #include <ext/stdio_filebuf.h>
int main() { int sockfd = socket(AF_INET, SOCK_STREAM, 0); sockaddr_in address; address.sin_family = AF_INET; address.sin_addr.s_addr = inet_addr("127.0.0.1"); address.sin_port = htons(119); int result; result = connect(sockfd, (sockaddr*)(&address), sizeof(address)); if (result != 0) { std::cerr << "connect failed " << std::endl; exit(1); }
__gnu_cxx::stdio_filebuf<char> sockBuf (sockfd, std::ios_base::in | std::ios_base::out); std::iostream sock(&sockBuf); std::string in; std::getline(sock, in); // succeeds std::cout << in << std::endl; if (!sock.good()) { std::cerr << "socket is not good\n"; } sock << "help\n"; // fails if (sock.bad()) { std::cerr << "write failed badly\n"; }
in.clear(); sock.clear(); std::getline(sock, in); // hangs std::cerr << "have read\n"; }
This program connects to a local newsserver, that gives an informative message first, and outputs more text after receiving the "help" message.
While the first getline works, the write does not, and "write failed badly" is output. Then the second getline hangs forever.
When I do the same thing using the low-level read and write functions instead of stdio_filebuf it works flawlessly.
Any clue about this issue is appreciated.
Best regards
Jochen