1

I'm writing a program that would create multiple TCP connections to a given IP address. For now, all the program has to do is connect. This is my first time doing something multithreaded in C and I've run into some behavior I cannot understand. If I set a breakpoint at the any line in the connection_handler function, it seems like in only gets called once, no matter what the num_clients is. Also, it seems like not all code in connection_handler gets executed.

struct client_data {
    int id;
    in_addr_t ip;
    int port;
};

int main(int argc, char **argv)
{
    int num_clients,
        port;
    in_addr_t ip;

    num_clients = atoi(argv[1]);
    ip = inet_addr(argv[2]);
    port = atoi(argv[3]);

    struct client_data clients[num_clients];
    pthread_t threads[num_clients];

    for (int i = 0; i < num_clients; i++) {
        clients[i].id = id;
        client[i].ip = ip;
        client[i].port = port;
        setup_client_struct(i, ip, port, &clients[i]);
        pthread_create(&threads[i], NULL, connection_handler, (void *) &clients[i]);
    }

    return EXIT_SUCCESS;
}

void error(char *msg)
{
    fprintf(stderr, "%s\n", msg);
    exit(EXIT_FAILURE);
}

void * connection_handler(void *thread_arg)
{
    int sock_fd;
    struct client_data *data;
    struct sockaddr_in serv_addr;

    data = (struct client_data *) thread_arg;
    sock_fd = socket(AF_INET, SOCK_STREAM, 0);

    if (sock_fd < 0) error("Error creating socket");

    bzero((char *) &serv_addr, sizeof (serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = data->ip;
    serv_addr.sin_port = data->port;

    if (connect(sock_fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
        error("Error connecting");
    }
    else {
        printf("Thread No. %d connected\n", data->id);
    }

    close(sock_fd);

    return 0;
}
iehrlich
  • 3,572
  • 4
  • 34
  • 43
PoVa
  • 995
  • 9
  • 24

1 Answers1

2

Add following code before line return EXIT_SUCCESS; of main() function :

for (int i = 0; i < num_clients; i++) {
    pthread_join(threads[i], NULL);
}

Above line of code will help to wait the main thread until all the other created threads are finished with their execution.

cse
  • 4,066
  • 2
  • 20
  • 37