echod_multithread.c

TIME_WAITがたまっていくけど、いいのかなぁ・・・

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <unistd.h>

#include <pthread.h>

#include <errno.h>

#define ECHO_PORT 7
#define MAX_BACKLOG 5
#define RCVBUFSIZE 256

#define die(s) do { fprintf(stderr, "%s\n", (s)); exit(1); } while(0)
#define die_with_err(s) do { perror((s)); exit(1); } while(0)

#ifdef DEBUG
#define debug(...) do { fprintf(stderr,  __VA_ARGS__); } while(0)
#else
#define debug(...) do {} while(0)
#endif

void *echo(void *arg) {
  int sock = (int) arg;
  debug("echo() bgein.\n");

  while (1) {
    char buf[RCVBUFSIZE + 1];
    size_t len;

    if ((len = recv(sock, buf, RCVBUFSIZE, 0)) < 0) {
      perror("recv(2)");
      return NULL;
    }

    if (len == 0) { break; }

    buf[len] = '\0';
    debug("recv: %s.\n", buf);

    if (send(sock, buf, len, 0) < 0) {
      perror("send(2)");
      return NULL;
    }
  }

  close(sock);
  debug("echo() end.\n");
  return NULL;
}

int main() {
  int sock;
  struct sockaddr_in addr;

  if ((sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) {
    die_with_err("socket(2)");
  }

  memset(&addr, 0, sizeof(addr));
  addr.sin_family = AF_INET;
  addr.sin_addr.s_addr = htonl(INADDR_ANY);
  addr.sin_port = htons(ECHO_PORT);

  if (bind(sock, (struct sockaddr*) &addr, sizeof(addr)) < 0) {
    die_with_err("bind(2)");
  }

  if (listen(sock, MAX_BACKLOG) < 0) {
    die_with_err("listen(2)");
  }

  while (1) {
    int s;
    struct sockaddr_in sa;
    socklen_t len = sizeof(sa);
    pthread_t thread;
    pthread_attr_t thread_attr;

    if ((s = accept(sock, (struct sockaddr*) &sa, &len)) < 0) {
      if (EINTR == errno) { continue; }
      die_with_err("accept(2)");
    }

    debug("accepted.\n");

    if (pthread_attr_init(&thread_attr) != 0) {
      die("pthread_attr_init(3): Failed");
    }

    if (pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED) != 0) {
      die("pthread_attr_setdetachstate(3): Failed");
    }

    if (pthread_create(&thread, &thread_attr, echo, (void *) s) != 0) {
      die("pthread_create(3): Failed");
    }

    pthread_attr_destroy(&thread_attr);
  }

  close(sock);
}