use*_*382 -1 c sockets multithreading network-programming
我正在尝试创建一个侦听套接字连接的进程.当我在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");
}
}
Run Code Online (Sandbox Code Playgroud)
奇怪的是,当我尝试通过调试器运行它时,有时候listener()的一部分会执行,然后就会停止.
你需要让线程有机会运行.您的程序main
在创建线程后立即终止(通过返回)!
如果您希望您的初始线程终止并让其他线程继续运行,请调用pthread_exit
而不是返回main
.如果您希望该线程等到侦听线程终止,请调用pthread_join
侦听线程.
您让初始线程离开地图的边缘.有龙.
归档时间: |
|
查看次数: |
1340 次 |
最近记录: |