标签:
UNPv3上一共总结了9种服务器模型分别是:
1.迭代服务器
典型代码: socket bind listen for(;;) { connfd = accept(listenfd, (SA*)&cliaddr, &clilen); process_connection(connfd); close(connfd); }
典型代码: init_address(server_addr) listenfd = socket(AF_INET,SOCKET_STREAM,0); bind(listenfd, (SA*)server_addr, sizeof(serveraddr)); listen(listenfd,BACKLOG); for(;;) { connfd = accept(listenfd, (SA*)&cliaddr, &clilen); if(connfd < 0) { if(EINTR == errno) continue; else //error } if(fork() == 0) { close(c=listenfd); process_connection(connfd); //child process exit(0); } close(connfd);//parent, close connected socket }
典型代码: static pthread_mutex_t *mptr; void my_lock_init(char *pathname) { int fd; pthread_mutexattr_t mattr; //因为是相关进程所以可以使用/dev/zero设备创建共享内存 //优势是调用mmap创建共享存储区之前无需一个实际的文件 //映射/dev/zero自动创建一个指定长度的映射区 fd = open("/dev/zero", O_RDWR, 0,); // 将mptr映射到共享存储区 mptr = mmap(0, sizeof(pthread_mutex_t), PORT_READ | PORT_WRITE, MAP_SHARED, fd, 0); close(fd); pthread_mutexattr_init(&mattr); pthread_mutexattr_setpshared(&mptr, PTHREAD_PROCESS_SHARED); pthread_mutex_init(mptr, &mattr); } void my_lock_wait() { pthread_mutex_lock(mptr); } void my_lock_release() { pthread_mutex_unlock(mptr); } int main(int argc, char **argv) { //init socket and address my_lock_init(pathname); for(i = 0; i < nchildren; ++i) { pids[i] = child_make(i, listenfd, addrlen); } for(;;) pause(); } pid_t child_make(int i, int listenfd, int addrlen) { pid_t pid; if((pid = fork) > 0) return pid; child_main(i, listenfd, addrlen); } void child_main() { for(;;) { my_lock_wait(); connfd = accept(listenfd, chiladdr, &clilen); my_lock_release(); web_child(connfd); close(connfd); } }
典型代码: for(;;) { connfd = accept(listenfd, cliaddr, &clilen,); pthread_create(&tid, NULL, &doit, (void *)connfd); } void * doit(void *arg) { pthread_detach(pthread_self()); web_child((int)arg); close((int)arg) return (NULL); }
标签:
原文地址:http://www.cnblogs.com/davygeek/p/4345782.html