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;
}