嵌入式C语言linux:服务器使用多线程为客户端提供服务,客户端发送任意一个正整数,服务器端返回此数因子的个数。
时间: 2023-06-03 07:02:44 浏览: 98
这个问题可以回答。以下是伪代码实现:
```c
#include <stdio.h>
int count_factors(int num) {
int count = 0;
for (int i = 1; i <= num; i++) {
if (num % i == 0) {
count++;
}
}
return count;
}
void *handle_client(void *arg) {
int client_socket = *(int *) arg;
while (1) {
int num;
if (recv(client_socket, &num, sizeof(num), 0) <= 0) {
// Error or client closed connection
close(client_socket);
return NULL;
}
int count = count_factors(num);
if (send(client_socket, &count, sizeof(count), 0) <= 0) {
// Error or client closed connection
close(client_socket);
return NULL;
}
}
}
int main() {
// Create server socket and bind to port
// Listen for incoming connections
while (1) {
int client_socket = accept(listening_socket, NULL, NULL);
if (client_socket < 0) {
// Error accepting connection
continue;
}
pthread_t thread_id;
pthread_create(&thread_id, NULL, handle_client, &client_socket);
pthread_detach(thread_id);
}
// Close listening socket
return 0;
}
```
阅读全文