Commit 335fbce4 authored by Seblu's avatar Seblu
Browse files

Readline correct avec mutex sur la socket

parent df432884
Loading
Loading
Loading
Loading
+1 −1
Original line number Diff line number Diff line
@@ -13,7 +13,7 @@ AM_INIT_AUTOMAKE([foreign dist-bzip2 no-dist-gzip])
# Check platform
AC_CANONICAL_HOST

CXXFLAGS='-Wall -W -ansi -pedantic -D_XOPEN_SOURCE=600'
CXXFLAGS='-Wall -Wextra -ansi -pedantic -pipe -D_XOPEN_SOURCE=600'

# Check for C++ compiler
AC_LANG([C++])
+36 −5
Original line number Diff line number Diff line
@@ -3,6 +3,7 @@
#include <arpa/inet.h>
#include <netdb.h>
#include <errno.h>
#include <poll.h>

#include "slc.hh"
#include "options.hh"
@@ -122,9 +123,39 @@ void Connection::sendln(const char* buf, size_t len) {

string Connection::recvln() {
  assert(socket > 0);
  char buf[MAX_LINE_SIZE];

  do {
    // check EOL char
    size_t offset = rbuf_.find('\n');
    if (offset != string::npos) {
      string s = rbuf_.substr(0, offset);
      rbuf_.erase(0, offset + 1);
      return s;
    }

    // wait incoming data
    static struct pollfd spfd[1] = {{socket_, POLLIN|POLLPRI|POLLHUP|POLLERR, 0}};
    poll(spfd, 1, -1);

    // lock before read
    pthread_mutex_lock(&mtx_socket);
  read(socket_, buf, MAX_LINE_SIZE);

    // read data
    static char local_buf[MAX_LINE_SIZE];
    int ret = ::recv(socket_, local_buf, MAX_LINE_SIZE, MSG_DONTWAIT);

    // unlock
    pthread_mutex_unlock(&mtx_socket);
  return buf;

    if (ret == -1) {
      disconnect_();
      *local_buf = 0;
    }
    else local_buf[ret] = 0;

    // add read data in buffer
    rbuf_ += local_buf;

  } while (1);
  assert(1);
}
+1 −0
Original line number Diff line number Diff line
@@ -19,6 +19,7 @@ private:
  void disconnect_();
private:
  int socket_;
  string rbuf_;
};

#endif