socket的服务器/客户端模型——时间服务器的版本演进

来源:互联网 发布:微信做宣传的软件 编辑:程序博客网 时间:2024/06/09 09:11

 客户端的处理程序是相同的

talk_with_server_v1(int fd){//缓存数组char buf[50];int n;//从服务端读取50字节的数据到数组n=read(fd,buf,50);//将数组中的数据写入到标准输出 write(1,buf,n);}


服务端的程序

1.版本1:单进程版,直接从用time()系统调用读取时间

process_request_v1(int fd){//读取的时间time_t now;//用time系统调用获取当前时间//时间格式:是从1970年开始的计数time(&now);//将计数时间转换为方便阅读的时间格式char *cp = ctime(&now);//向客户端写入时间信息write(fd,cp,strlen(cp));}

2.版本2:多进程版 v2.1,基于v1的演进,采用多进程的处理方式

process_request_v21(int fd){int pid = fork();switch(pid){//新进程创建失败case -1:return;//如果创建成功,fork是双返回值,//对于父进程返回子进程ID,对于子进程返回0case 0:{                        time_t now;time(&now);char *cp = ctime(&now);write(fd,cp,strlen(cp));return;                }//父进程要做的只是等待子进程退出default:wait(NULL);}}

2.版本2:多进程版 v2.2,基于v2.1的演进,在多进程的基础之上,采用shell的date命令

process_request_v22(int fd){    int pid = fork();      switch(pid){                    //新进程创建失败           case -1:return;                    //如果创建成功,fork是双返回值,           //对于父进程返回子进程ID,对于子进程返回0           case 0:{              // dup fd to 1/* * we need to review the dup2 * the function of the dup2  * newfd = dup(oldfd); * it means we copy the oldfd to newfd * after dup,the newfd = oldfd * 多了一个描述符指向文件 * 此时,新旧描述符指向同一个打开文件 * * newfd = dup2(oldfd,newfd); * 将oldfd复制给newfd, * 两个描述符指向同一个文件 * */// 1是标准输出,把fd复制给标准输出// 此时标准输出1将不再指向屏幕// 而是对方的socket// 当然fd也指向dup2(fd,1);// fd无用了close(fd);// 执行shell程序execl("/bin/date","date",NULL);oops("execl");            return;  }        //父进程要做的只是等待子进程退出           default:wait(NULL);      } }