进程池模块让程序多进程并发执行,内存中多进程同时处理用户请求。
nt main(void)
{
int procNum=0; /*内存中运行的子进程数*/
pid_t pid;
int i=0;
signal(SIGCLD,SIG_DFL);
while(i<100)
{
while(procNum>MAXPRO);/*当进程池满,则父进程一直等待,不创建新子进程*/
pid=fork();
if(pid<0)
{
printf("Create PID err\n");
return -1;
}
procNum++;
if(0==pid)
{ /*子进程 user code here*/
pid=getpid();
printf("PID=[%d]\n",pid);
sleep(2);
/*手动退出子进程*/
exit(0);
}
if(procNum>MAXPRO){ /*进程池满,等待子进程退出,退出一个则procNum--*/
/*wait(NULL);*/
int stat_loc;
waitpid(-1, &stat_loc, 0);
if( WEXITSTATUS( stat_loc ) || WIFSIGNALED( stat_loc ) )
{
printf("Child PID err\n");
return -1;
}
procNum--;
}
printf("PROCNUM [%d]\n",procNum);
i++;
}
while(wait(NULL)!=-1); /*等待所有子进程退出*/
signal(SIGCLD,SIG_IGN);
return 0;
}