今天总结了下进程池,和大家分享一下,感觉初学者因该能比较好理解。
进程池,顾名思义是一个装有进程的池子,池子有固定大小,也就是工作进程的数量,进程池的工作就是管理它自己这个池子。
进程池基本工作机制是:当进程池启动时,就创建规定数量的进程(自己设定合适数量),等待在那里;当有任务来的时候,进程池分配任务给空闲进程,空闲进程-->工作进
程;当工作进程完成所分配任务后,进程池回收空闲进程,工作进程-->空闲进程。
下面是我用进程池实现TCP网络通讯的实例:
调试的时候请按照这样编译 gcc processpool.c -o processpool
gcc tcpcli.c - o tcpcli
//第一个文件processpool.c
#include <time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <signal.h>
#include <sys/wait.h>
#include <pthread.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#define INITCHILD -1
#define PRECHILD 5
#define MAXCHILD 50
#define BUFSIZE 4096
#define PIDPATH "processpool"
#define PORT 33445
int fd1[2];
int fd2[2];
typedef struct processinfo
{
pid_t pid;
int status; //1:完成空闲 0:工作
}processinfo;
void printerror(char *msg)
{
//perror("%s:\n",msg);
perror(msg);
return ;
}
//设置成守护进程
void daemon_init()
{
pid_t pid;
pid=fork();
if(pid>0)
exit(-1);
setsid();
pid=fork();
if(pid>0)
exit(-1);
umask(0);
int i;
for(i=0;i<1024;i++)
close(i);
}
//防止一次只能有一个进程运行
int isrunning()
{
int fd;
fd=open(PIDPATH,O_RDONLY);//只能是O_RDONLY
if(fd<0)
{
return -1;