特点
-
可以同时处理多个客户端请求,创建子进程或者分支线程来处理客户端的请求
-
父进程/主线程只负责连接,子进程/分支线程只负责与客户端进行交互;
多进程并发服务器框架:
void handler(int sig)
{
//回收僵尸进程
//回收成功则再回收一次,直到回收失败或者没有回收到为止
while(waitpid(-1, NULL, WNOHANG) > 0);
}
//捕获17号信号 SIGCHLD
sighandler_t s = signal(17, handler);
sfd = socket();
bind();
listen();
while(1)
{
newfd = accept();
pid = fork();
if(pid > 0)
{
close(newfd);
}
else if(0 == pid)
{
close(sfd);
while(1)
{
recv();
send();
}
close(newfd);
exit(0);
}
}
close(sfd);
多线程并发框架
sfd = socket();
bind();
listen();
struct msg cliInfo;
while(1)
{
newfd = accept();
cliInfo.newfd = newfd;
pthread_create(&tid, NULL, callback, &cliInfo);
}
void* callBack(void* arg)
{
pthread_detach(pthread_self());
while(1)
{
recv();
send();
}
close(newfd);
pthread_exit()
}