multithreading - C: pthread failing to listen, bind, and accept on a socket -
i trying create process listen connections on socket. seems work when bind, listen, , wait accepts in main() function. when attempt create new thread , bind, listen, , accept on new thread, fails. here code.
void request_handler(int clientsock) { file *requestedfile = null; long filesize = 0; struct stat st; long bytesread; char buffer[1024]; requestedfile = fopen("/path/book.txt", "rb"); while(!feof(requestedfile)) { bytesread = fread(buffer, 1, sizeof(buffer), requestedfile); send(clientsock, buffer, bytesread, 0); } } void listener() { int server_sock_desc; struct sockaddr_in name; int client_sock_desc; struct sockaddr_in client_name; socklen_t addr_size; pthread_t handler_thread; printf("waiting"); //connection setup server_sock_desc = socket(pf_inet, sock_stream, 0); if(server_sock_desc != -1) { memset(&name, 0, sizeof(name)); name.sin_family = af_inet; name.sin_port = htons(5000); name.sin_addr.s_addr = htonl(inaddr_any); int bind_result = bind(server_sock_desc, (struct sockaddr *) &name, sizeof(name)); if(bind_result == 0) { if(listen(server_sock_desc, backlog) < 0) { perror("listen failed"); } addr_size = sizeof(client_name); //server loop continue run listening clients connecting server while(1) { //new client attempting connect server client_sock_desc = accept(server_sock_desc, (struct sockaddr *) &client_name, &addr_size); if(client_sock_desc == -1) { if(errno == eintr) { continue; } else { perror("accept failed"); exit(1); } } //connection starts here //create thread new clients request handled if(pthread_create(&handler_thread, null, request_handler, client_sock_desc) != 0) { perror("pthread_create failed"); } } } else { perror("bind failed"); } } else { perror("socket failed"); } } int main(int argc, const char * argv[]) { pthread_t listenerthread; if(pthread_create(&listenerthread, null,listener, null) != 0) { perror("listener thread create failed"); } }
the weird thing is, when try run through debugger, part of listener() execute, stop out of nowhere.
you need give thread chance run. program terminates (by returning main
) right after creating thread!
if want initial thread terminate , leave other thread running, call pthread_exit
rather returning main
. if want thread wait until listening thread terminates, call pthread_join
on listening thread.
you let initial thread run off edge of map. there dragons.
Comments
Post a Comment