【发布时间】:2012-02-16 03:49:38
【问题描述】:
所以我想在 linux 内核 2.6.x 下使用套接字将多个客户端连接到服务器。 当客户端连接时,服务器将向客户端发送欢迎消息,以显示在标准输出或任何内容上的方式。因此,当连接打开时,一个线程被分配给一个可能向客户端发送欢迎消息的函数非常客户端。当我使用另一个处理器来完成这项工作时,它很好。但是,当我切换到 pthread 方式时,客户端无法从服务器获取任何东西。此时,我检查了 netstat,连接仍然on.so 我的代码来了:
client.c
// to make long story short,
// i'll just omit most of declarations and stuff that is irrelavent to the problem
#define PORT 12345
#define IP_ADDR "127.0.0.1"
void *process_to_server(int socket);
int main(){
// i'll skip building socket for your convinence
process_to_server(socket_server);
}
void *process_to_server(int socket){
ssize_t size=0;
char buffer[1024];
size=read(socket,buffer,1024);
write(1,buffer,size+1);// output the welcome message to the client's standard output
}
服务器.c
#define PORT 12345
void *process_to_client(int socket);
int main(){
// same spirit as above
while(1){
int addrlen=sizeof(struct sockaddr);
socket_client = accept(socket_server,(struct sockaddr*)&client_addr,&addrlen);
if(socket_client<0) continue;
pthread_t pth;
close(socket_server);
pthread_create(&pth,NULL,(void*)&process_to_client,&socket_client);
}
}
void *process_to_client(int socket){
char buffer[1024];
sprintf(buffer,"Hello There\n");
write(socket,buffer,1024);
}
【问题讨论】:
-
为什么是
close(socket_server);?