在添加fork()之前,下面的代码运行正常但在调用fork()之后,服务器无限运行。我希望服务器在服务特定数量的客户端后退出,并希望服务器此后终止。
for(count = 0; count < 2; count++)
{
client_socket = accept(server_socket, NULL, NULL);
if(fork() == 0)
{
printf("from Server\n");
}
close(client_socket);
}
close(server_socket);
}
答案 0 :(得分:1)
它似乎想要为特定数量的客户端提供服务然后终止,请尝试:
#define MAX_CLIENTS 3
for(count = 0; count < MAX_CLIENTS; count++)
{
client_socket = accept(server_socket, NULL, NULL);
if(fork() != 0)
{
/*Thats parent it will go back listening*/
printf("from Server\n");
}
else
{
/*Thats child it will Serv the client and terminate*/
close(client_socket);
exit(0);
}
}
close(server_socket);