我正在尝试创建一个侦听套接字连接的进程。当我在main()函数中绑定,监听和等待接受时,它似乎有效。但是当我尝试创建一个新线程并在新线程上绑定,监听和接受时,它就失败了。这是我的代码。
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 will continue to run listening for clients connecting to the server
while(1) {
//new client attempting to connect to the 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 a thread for the new clients request to be 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");
}
}
奇怪的是,当我尝试通过调试器运行它时,有时候listener()的一部分会执行,然后就会突然停止。
答案 0 :(得分:5)
您需要为线程提供运行的机会。您的程序在创建线程后立即终止(通过从main
返回)!
如果您希望初始线程终止并让其他线程继续运行,请调用pthread_exit
而不是从main
返回。如果您希望该线程等到侦听线程终止,请在侦听线程上调用pthread_join
。
让初始线程离开地图的边缘。有龙。