I am trying to write a server program that creates a process for processing several client connections that creates one thread for each connection. But the maximum number of threads created by this process never exceeds 382.
Why can't I create more threads that process a single file descriptor to communicate with a single client, while the file descriptor limit on a process is 1024 in Linux?
I am using a Kubuntu-based system on Core-i3 with 2 GB of RAM.
Here is the code for the main function.
int server_start(void)
{
listen(skid,10000);
scnt=0;
printf("Server Listening at port:%d\n",serdt.port);
for(scnt=0;scnt<1000;)
{
sdata->cpid[scnt]=fork();
switch(sdata->cpid[scnt])
{
case -1: printf("Could not Fork\n"); break;
case 0: mxsubserver(scnt); exit(0);
default: scnt++; break;
}
pause();
}
while(1);
}
A variable not declared in a function is a global variable. I have an empty handler for signal number 50 to exit pause.
() , ( ), . , fork ...
typedef struct
{
int cln;
int cnt;
int fd;
pthread_t ptid;
}service_d;
void mxsubserver(int cln)
{
int ln,fd,rfp;
pthread_t ptid;
pthread_attr_t attr;
iflag=1;
sub_data = shmat(shmid,NULL,SHM_RND);
signal(SIGINT,sub_sigint);
signal(SIGPIPE,sub_sigpipe);
signal(50,SIG_DFL);
parg = malloc(sizeof(service_d));
parg->cln = cln;
cnt=0;
printf("Server Instance %d Started\n",cln);
for(cnt=0;;)
{
if(iflag)
{
cnt++;
ln = (socklen_t)sizeof(struct sockaddr_in);
fd = accept(skid,(struct sockaddr *)&sktaddr,&ln);
parg->fd=fd;
parg->cnt=(cln*1000)+cnt;
pthread_attr_init(&attr);
pthread_create(&(parg->ptid),&attr,&service,parg);
pthread_detach(parg->ptid);
pthread_attr_destroy(&attr);
sub_data->openfd[cln]=cnt;
}
if(cnt>=1000)
{
printf("Limit Reached\n");
iflag=getppid();
printf("Signalling Parent\n");
kill(iflag,50);
iflag=0;
pause();
}
if(cnt==0)
{
free(parg);
exit(0);
}
}
kill(getppid(),50);
while(1);
return;
}
void sub_sigint(int sn)
{
free(parg);
shmdt(sub_data);
exit(0);
}
void sub_sigpipe(int sn)
{
cnt--;
iflag=1;
}
void* service(void *arg)
{
int fd,cln,l,ol;
char im[100],*msg="This is from Server\n";
service_d *srd;
srd = (service_d*)arg;
fd = srd->fd;
cln = srd->cnt;
printf("service cln: %d f: %d\n",cln,iflag);
ol=strlen(msg);
while(1)
{
read(fd,&l,sizeof(int));
if(read(fd,im,l)<0) break;
im[l]='\0';
if(write(fd,&ol,sizeof(int))<0) break;
if(write(fd,msg,ol)<0) break;;
}
close(fd);
pthread_exit("Done\n");
}
.