这个与上一节的程序相比很简单,就是将循环中Accept()以后的运行程序,让子进程来完成。由fork()程序来创建子进程。父进程基本不做工作(除了必须关闭相关的套接字)。其中必须声明新的变量pid_t pid;
for(;;){
len = sizeof(cliaddr);
connfd = Accept(listenfd,(SA *)&cliaddr,&len);
if( (pid = Fork()) == 0){ //完全交给子程序去处理
Close(listenfd); //千万要记得将监听到截止关掉,已经没用
printf("connection from %s,port %d\n",
inet_ntop(AF_INET,&cliaddr.sin_addr,buf,sizeof(buf)),
ntohs(cliaddr.sin_port)
);
ticks = time(NULL);
snprintf(buf,sizeof(buf),"%.24s\t\n",ctime(&ticks));
Write(connfd,buf,strlen(buf));
Close(connfd);
exit(0);
}
Close(connfd);
}
完整服务器代码
#include "unp.h"
#include <unistd.h>
int main(int argc,int **argv)
{
int listenfd,connfd;
socklen_t len;
struct sockaddr_in servaddr,cliaddr;
char buf[MAXLINE];
time_t ticks;
pid_t pid;
listenfd = socket(AF_INET,SOCK_STREAM,0);
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(13);
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
Bind(listenfd,(SA *)&servaddr,sizeof(servaddr));
Listen(listenfd,LISTENQ);
for(;;){
len = sizeof(cliaddr);
connfd = Accept(listenfd,(SA *)&cliaddr,&len);
if( (pid = Fork()) == 0){ //完全交给子程序去处理
Close(listenfd); //千万要记得将监听到截止关掉,已经没用
printf("connection from %s,port %d\n",
inet_ntop(AF_INET,&cliaddr.sin_addr,buf,sizeof(buf)),
ntohs(cliaddr.sin_port)
);
ticks = time(NULL);
snprintf(buf,sizeof(buf),"%.24s\t\n",ctime(&ticks));
Write(connfd,buf,strlen(buf));
Close(connfd);
exit(0);
}
Close(connfd);
}
return 0;
}