I'm writing program in UNIX on C. I have to write client-server(TCP) program on sockets. Client sends some information and server answer. No matter what client sends or receives because I successfully wrote code for it. But last part of task is very hard for me.
1)One connection - one child process.
2)For new connections using pre-running processes from a pool.
3)Pool size is dinamic.If the number of free processes(which is not servicing client) became less than N - should create new processes, if it became more than K - "extra" processes must be terminated.
This is my code. Every connection make new child process using fork()
.Each connection runs in new process. But how to make dynamic pool that I said above?
Please, help, it's very important! This is the last what I should do.
Server Code:
int main(int argc, char * argv[])
{
int cfd;
int listener = socket(AF_INET, SOCK_STREAM, 0); //create listiner socket
if(listener < 0){
perror("socket error");
return 1;
}
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(PORT);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
int binding = bind(listener, (struct sockaddr *)&addr, sizeof(addr));
if(binding < 0){
perror("binding error");
return 1;
}
listen(listener, 1); //listen for new clients
signal(SIGCHLD,handler);
int pid;
for(;;) // infinity loop on server
{
cfd = accept(listener, NULL, NULL); //client socket descriptor
pid = fork(); //make child proc
if(pid == 0) //in child proc...
{
close(listener); //close listener socket descriptor
... //some server actions that I do.(receive or send)
close(cfd); // close client fd
return 0;
}
close(cfd);
}
return 0;
}