0

Basically I want the program to exit when I send the "exit" command. As of now once the thread_callback function finishes after the exit command is sent the main loop does not immediately exit, instead it exits on the next client connection. Any idea how I could solve this?

I do not wish to use pthread_join or the exit function.

Thanks.

void *thread_callback(void *client_data) {
  int client_id = *(int *)client_data;
  char some_buffer[BUFFER_SIZE];

  printf("thread %p\n", (void *)pthread_self());

  while (exit_flag != 1) {
    int len = recv(client_id, some_buffer, BUFFER_SIZE, 0);

    if (len > 0) {
        printf("%.*s\n", len, some_buffer);

        if (strcmp("exit", some_buffer) == 0)
            exit_flag = 1;
    }
  }

  pthread_exit(NULL);
}

int main(int argc, char **argv) {
  int server_socket;
  int client_socket;

  server_socket = create_tcp_server();

  while (exit_flag != 1) {
    pthread_t thread_id;

    client_socket = accept(server_socket, NULL, 0);

    if (client_socket > 0) {
        pthread_create(&thread_id, NULL, &thread_callback, (void *)&client_socket);
        pthread_detach(thread_id);
    }
  }

  return 0;
}
5
  • 1
    Your code doesn't compile, since there is no variable named exit_flag. Commented Dec 6, 2013 at 23:39
  • accept waits for the next client connection. Therefore, the while condition won't be tested until accept finishes. Commented Dec 6, 2013 at 23:39
  • Why not just call exit() on receiving "exit". Commented Dec 6, 2013 at 23:51
  • @alk Perhaps he wants to add more code in his main function. No need to limit yourself. Commented Dec 6, 2013 at 23:53
  • Other issues: read() returns ssize_t but int; passing the address of client_socket introduces a race between the threads created. Commented Dec 6, 2013 at 23:54

1 Answer 1

1

You should pass the server_socket to the thread as well, then:

if (strcmp("exit", some_buffer) == 0) {
      exit_flag = 1;
      shutdown(server_socket, 0);
}

shutdown will make accept to return.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.