Advertisement
Guest User

Untitled

a guest
Jan 16th, 2017
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.35 KB | None | 0 0
  1. void *thread_handle_connection(void *arg) {
  2. char buffer[MAX_MSG_SIZE]; // Receive buffer
  3. int bytes_read;
  4.  
  5. do {
  6.  
  7. // If there aren't any connections, sleep and recheck every second
  8. while(!num_connections && !term_requested) {
  9. sleep(1);
  10. }
  11.  
  12. // Lock out connections queue and grab the first one
  13. pthread_mutex_lock(&queue_mutex);
  14. int connectionfd = remove_connection_from_queue();
  15. pthread_mutex_unlock(&queue_mutex);
  16.  
  17. if(-1 == connectionfd) {
  18. continue;
  19. }
  20.  
  21. // pthread_barrier_wait(&barrier); // Barrier for threads - for testing only
  22.  
  23. // Read up to 1024 bytes from the client
  24. bytes_read = recv(connectionfd, buffer, MAX_MSG_SIZE - 1, 0);
  25.  
  26. // If the data was read successfully
  27. if(bytes_read > 0) {
  28. // Add a terminating NULL character and print the message received
  29. buffer[bytes_read] = '';
  30.  
  31. // Calculate response
  32. int multiplicand = atoi(buffer);
  33. char *response;
  34. asprintf(&response, "%d", multiplicand * MULTIPLIER);
  35.  
  36. // Echo the data back to the client; exit loop if we're unable to send
  37. if(-1 == send(connectionfd, response, strlen(response), 0)) {
  38. warn("Unable to send data to client");
  39. break;
  40. }
  41. free(response);
  42. }
  43.  
  44. // Close connection
  45. close(connectionfd);
  46.  
  47. } while(bytes_read > 0 && !term_requested);
  48.  
  49. return NULL;
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement