通过静态进程池实现NTP服务器
例程:server.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <time.h>
#include <unistd.h>
#include "proto.h"
#define PIDCOUNT 4
#define IPSIZE 40
static void sock_loop(int lfd);
static void func(int fd) //获取时间戳发送给客户端
{
FILE *fp = fdopen(fd,"r+");
fprintf(fp,FMT,(long long)time(NULL));
fclose(fp);
}
int main()
{
int ret,i;
int lfd;
struct sockaddr_in laddr;
char ip[IPSIZE];
pid_t pid;
lfd = socket(AF_INET,SOCK_STREAM,0); //创建socket
if(lfd <0)
{
perror("socket()");
exit(1);
}
int val =1;
ret = setsockopt(lfd,SOL_SOCKET,SO_REUSEPORT,&val,sizeof(val)); //设置端口复用
if(ret <0)
{
perror("setsockopt()");
exit(1);
}
laddr.sin_family = AF_INET; //初始化结构体
laddr.sin_port = htons(atoi(PORT));
inet_pton(AF_INET,"0.0.0.0",&laddr.sin_addr.s_addr);
ret = bind(lfd,(void *)&laddr,sizeof(laddr)); //绑定端口和IP
if(ret<0)
{
perror("bind()");
exit(1);
}
ret = listen(lfd,200); //监听 最大监听200个
if(ret <0)
{
perror("listen()");
exit(1);
}
for(i=0;i<PIDCOUNT;i++) //循环创建子进程
{
pid = fork();
if(pid<0)
{
perror("fork()");
exit(1);
}
if(pid ==0)
{
sock_loop(lfd); //子进程任务
}
}
for(i=0;i<PIDCOUNT;i++) //等待子进程结束
wait(NULL);
exit(0);
}
static void sock_loop(int lfd)
{
struct sockaddr_in raddr;
socklen_t lenth;
char ip[IPSIZE];
int newfd;
lenth = sizeof(raddr);
while(1)
{
newfd = accept(lfd,(void *)&raddr,&lenth); //等待客户连接
if(newfd<0)
{
perror("accpt()");
break;
}
inet_ntop(AF_INET,&raddr.sin_addr.s_addr,ip,IPSIZE);
printf("-----pid:%d IP:%s PORT:%d-----\n",getpid(),ip,ntohs(raddr.sin_port)); //打印客户端信息
func(newfd); //任务
}
}
其他参考: