Sockets and streams using C

I am new to both sockets and threads. I have this code:

listen(socket_fd, 20);

/* Looooop */
  while (1) {
    newsocket_fd = accept(socket_fd, 
                          (struct sockaddr *) &client_addr, 
                          &client_len);
    if (newsocket_fd < 0) {
      error("ERROR on accept");
    }
    pthread_t thread;
    pthread_create(&thread, NULL, run_thread, (void *) newsocket_fd);
    pthread_join(thread, NULL);
  }

How can I start a new thread for each new connection, and not for each request? These threads should start when a new connection arrives, and these threads should wait for requests, process these requests, and finally return when the connection is closed. There must be one thread for each connection. Here is the code for run_thread:

void
*run_thread(void *ptr) {
  char buffer[256];
  bzero(buffer, 256);
  int n;
  n = read((int) ptr, buffer, 255);
  if (n < 0) error("ERROR Reading from socket");
  printf("%s\n\n**********\n\n", buffer);

  /* Parse buffer and return result */
  char *result;
  {
    /* First, determine command, 4 characters */
    /* (much code) */
  }

  n = write((int) ptr, result, strlen(result));
  if (n < 0) error("ERROR Writing to socket");
}

Can anyone help me? Thank.

+3
source share
3 answers

. , , , , pthread_join , . , , . , . . , pthread_attr_init pthread_create.

, , . , . TCP/IP -. C, ++ -, boost:: asio.

+7

.

int (void *). . , , accept(), . :

while (1) {
    newsocket_fd = accept(socket_fd, 
                          (struct sockaddr *) &client_addr, 
                          &client_len);
    if (newsocket_fd < 0) {
      error("ERROR on accept");
    }
    pthread_t thread;
    int *newsock = malloc(sizeof(int));
    *newsock = newsocket_fd;
    pthread_create(&thread, NULL, run_thread, newsock);
    pthread_detach(thread);
  }

, () . ,

void *handler(void *thread_data) {
   int fd = *(int *) thread_data;
   free(thread_data);
   ....
}

, , pthread_detach() , pthread_join().

+5

.

, newsocket_fd accept, . .

EDIT: , , . newsocket_fd.

0

Source: https://habr.com/ru/post/1764922/


All Articles