Linux下并发网络设计之I/O复用
I/O 流:
首先我们来定义流的概念,一个流可以是文件,socket,pipe等等可以进行I/O操作的内核对象。
/*epoll+线程池 服务器端例程*/
1 #include <unistd.h>
#include <sys/types.h> /* basic system data types */
#include <sys/socket.h> /* basic socket definitions */
#include <netinet/in.h> /* sockaddr_in{} and other Internet defns */
#include <arpa/inet.h> /* inet(3) functions */
#include <sys/epoll.h> /* epoll function */
#include <fcntl.h> /* nonblocking */
#include <sys/resource.h> /*setrlimit */ #include <pthread.h>
#include <assert.h> #include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#include <string.h> #define MAXEPOLLSIZE 10000
#define MAXLINE 10240 typedef struct msgdata{
char name[];
int connfd;
char buffer[BUFSIZ];
char target[];
struct msgdata *next;
}Msg; typedef struct worker{
//回调函数,任务运行时会调用此函数,也可以声明为其他形式
//该函数参数是任意类型的, 参数也是任意类型的;
void * (*process)(void *arg);
void *arg;
struct worker *next;
}CThread_worker; //线程池结构
typedef struct{
pthread_mutex_t queue_lock; //互斥量
pthread_cond_t queue_ready; //条件变量 //链表结构, 线程池中所有等待任务
CThread_worker *queue_head; //是否销毁线程池
int shutdown;
pthread_t *threadid; //线程池中允许的活动线程数目
int max_thread_num;
//当前等待队列的任务数目
int cur_queue_size;
}CThread_pool; int pool_add_worker(void * (*process)(void *arg), void *arg);
void * thread_routine(void *arg);
void * myprocess(void *arg); //全局静态的结构体指针
static CThread_pool *pool = NULL; void pool_init(int max_thread_num)
{
int i;
pool = (CThread_pool*)malloc(sizeof(CThread_pool));
//初始化互斥量
pthread_mutex_init(&(pool->queue_lock), NULL);
//初始化条件变量
pthread_cond_init(&(pool->queue_ready), NULL); pool->queue_head = NULL; //最大线程数目
pool->max_thread_num = max_thread_num;
//当前线程数目
pool->cur_queue_size = ; pool->shutdown = ;
pool->threadid = (pthread_t*)malloc(max_thread_num * sizeof(pthread_t)); for(i=; i<max_thread_num; i++)
{
pthread_create(&(pool->threadid[i]), NULL, thread_routine, NULL);
}
} int pool_add_worker(void * (*process)(void *arg), void *arg)
{
//构建一个新任务
CThread_worker *newworker = (CThread_worker *)malloc(sizeof(CThread_worker));
newworker->process = process;
newworker->arg = arg;
newworker->next = NULL; //加锁互斥量
pthread_mutex_lock(&(pool->queue_lock));
//将任务加入到等待队列中
CThread_worker *member = pool->queue_head;
if(member != NULL)
{
while(member->next != NULL)
member = member->next;
member->next = newworker;
}
else //此时 线程池中是空。
{
pool->queue_head = newworker;
} //此时,线程池中有任务
assert(pool->queue_head != NULL);
pool->cur_queue_size++;
pthread_mutex_unlock(&(pool->queue_lock)); //等待队列中有任务了,唤醒一个等待线程;
//如果此时所有线程都在忙碌,这句话没有任何作用,
//因为没有线程等待,怎么唤醒呢;
//pthread_cond_signal用于通知阻塞的线程某个特定的条件为真了
pthread_cond_signal(&(pool->queue_ready));
return ;
} int pool_destroy()
{
if(pool->shutdown)
return -; //防止调用两次
pool->shutdown = ; //唤醒所有等待线程,线程池要销毁了
pthread_cond_broadcast(&(pool->queue_ready)); //阻塞等待线程退出, 否则就称僵尸了;
int i;
for(i=; i<pool->max_thread_num; i++)
{
pthread_join(pool->threadid[i], NULL);
} free(pool->threadid);
//销毁等待队列
CThread_worker *head = NULL;
while(pool->queue_head != NULL)
{
head = pool->queue_head;
pool->queue_head = pool->queue_head->next;
free(head);
}
//条件变量 和 互斥量也要销毁
pthread_mutex_destroy(&(pool->queue_lock));
pthread_cond_destroy(&(pool->queue_ready)); free(pool);
//销毁后指针 置空是有必要的,但不是必须的
pool = NULL;
return ;
} //start thread 0x b7771b70 is waiting
//thread 0x b7771b70 is waiting
void * thread_routine(void *arg)
{
printf("start thread 0x %x is waiting \n", pthread_self());
while()
{
pthread_mutex_lock(&(pool->queue_lock));
//如果线程池中运行线程数目为0,并且不销毁线程池,则处于阻塞阻塞;
//注意:pthread_cond_wait是一个原子操作,等待前会解锁,唤醒后会加锁
while(pool->cur_queue_size == && !pool->shutdown)
{
printf("thread 0x %x is waiting \n", pthread_self());
//pthread_cond_wait用于等待某个特定的条件为真
pthread_cond_wait(&(pool->queue_ready), &(pool->queue_lock));
}
//线程池 要销毁了;
if(pool->shutdown)
{
//遇到break,continue,return等跳转语句,一定要先解锁
pthread_mutex_unlock(&(pool->queue_lock));
printf("thread 0x %x will exit\n", pthread_self());
pthread_exit(NULL);
}
printf("thread 0x %x is starting to work \n",pthread_self()); //使用断言
assert(pool->cur_queue_size != );
assert(pool->queue_head != NULL); //等待队列长度减去1, 并取出链表中的头元素
pool->cur_queue_size--;
CThread_worker *worker = pool->queue_head;
pool->queue_head = worker->next;
pthread_mutex_unlock(&(pool->queue_lock)); //调用回调函数,执行任务
(*(worker->process))(worker->arg);
//销毁线程函数;
free(worker);
worker = NULL;
printf("hello world\n");
}
//正常情况下,这里不能到达;
pthread_exit(NULL);
}
/////////////////////////////////////////////////////
int handle(int connfd); int setnonblocking(int sockfd)
{
if (fcntl(sockfd, F_SETFL, fcntl(sockfd, F_GETFD, )|O_NONBLOCK) == -) {
return -;
}
return ;
} int main(int argc, char **argv)
{
int servPort = ;
int listenq = ; int listenfd, connfd, kdpfd, nfds, n, nread, curfds,acceptCount = ;
struct sockaddr_in servaddr, cliaddr;
socklen_t socklen = sizeof(struct sockaddr_in);
struct epoll_event ev;
struct epoll_event events[MAXEPOLLSIZE];
struct rlimit rt;
char buf[MAXLINE]; //初始化线程池的相关操作
pool_init(); //线程池中最多3个活动的线程 /* 设置每个进程允许打开的最大文件数 */
rt.rlim_max = rt.rlim_cur = MAXEPOLLSIZE;
if (setrlimit(RLIMIT_NOFILE, &rt) == -)
{
perror("setrlimit error");
return -;
} bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(servPort); listenfd = socket(AF_INET, SOCK_STREAM, );
if (listenfd == -) {
perror("can't create socket file");
return -;
} int opt = ;
setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); if (setnonblocking(listenfd) < ) {
perror("setnonblock error");
} if (bind(listenfd, (struct sockaddr *) &servaddr, sizeof(struct sockaddr)) == -)
{
perror("bind error");
return -;
}
if (listen(listenfd, listenq) == -)
{
perror("listen error");
return -;
}
/* 创建 epoll 句柄,把监听 socket 加入到 epoll 集合里 */
kdpfd = epoll_create(MAXEPOLLSIZE);
ev.events = EPOLLIN | EPOLLET;
ev.data.fd = listenfd;
if (epoll_ctl(kdpfd, EPOLL_CTL_ADD, listenfd, &ev) < )
{
fprintf(stderr, "epoll set insertion error: fd=%d\n", listenfd);
return -;
}
curfds = ; printf("epollserver startup,port %d, max connection is %d, backlog is %d\n", servPort, MAXEPOLLSIZE, listenq); for (;;) {
/* 等待有事件发生 */
nfds = epoll_wait(kdpfd, events, curfds, -);
if (nfds == -)
{
perror("epoll_wait");
continue;
}
/* 处理所有事件 */
for (n = ; n < nfds; ++n)
{
if (events[n].data.fd == listenfd)
{
connfd = accept(listenfd, (struct sockaddr *)&cliaddr,&socklen);
if (connfd < )
{
perror("accept error");
continue;
} sprintf(buf, "accept form %s:%d\n", inet_ntoa(cliaddr.sin_addr), cliaddr.sin_port);
printf("%d:%s", ++acceptCount, buf); if (curfds >= MAXEPOLLSIZE) {
fprintf(stderr, "too many connection, more than %d\n", MAXEPOLLSIZE);
close(connfd);
continue;
}
if (setnonblocking(connfd) < ) {
perror("setnonblocking error");
}
ev.events = EPOLLIN | EPOLLET;
ev.data.fd = connfd;
if (epoll_ctl(kdpfd, EPOLL_CTL_ADD, connfd, &ev) < )
{
fprintf(stderr, "add socket '%d' to epoll failed: %s\n", connfd, strerror(errno));
return -;
}
curfds++;
continue;
}
// 处理客户端请求 这里进入线程池内,处理用户的操作
else
{
pool_add_worker(myprocess, &(events[n].data.fd));
}
}
}
pool_destroy();
close(listenfd);
return ;
}
/*
int handle(int connfd) {
int nread;
char buf[MAXLINE];
nread = read(connfd, buf, MAXLINE);//读取客户端socket流
if (nread == 0) {
printf("client close the connection\n");
close(connfd);
return -1;
}
if (nread < 0) {
perror("read error");
close(connfd);
return -1;
}
write(connfd, buf, nread);//响应客户端
return 0;
}
*/
//int handle(int connfd)
void * myprocess(void *arg)
{
//解包, 加锁把struct(用户名,connfd)放入链表,并在根据用户名在链表中
//对应的connfd,
int connfd = *((int *)arg);
int nread;
char buf[BUFSIZ];
nread = read(connfd, buf, MAXLINE);//读取客户端socket流
if (nread == )
{
printf("client close the connection\n");
close(connfd);
return NULL;
}
else if (nread < )
{
perror("read error");
close(connfd);
return NULL;
}
else
{ } write(connfd, buf, nread);//响应客户端
return NULL;
}
客户端例程:
#include <unistd.h>
#include <sys/types.h> /* basic system data types */
#include <sys/socket.h> /* basic socket definitions */
#include <netinet/in.h> /* sockaddr_in{} and other Internet defns */
#include <arpa/inet.h> /* inet(3) functions */
#include <netdb.h> /*gethostbyname function */ #include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#include <string.h> #define MAXLINE 1024 void handle(int connfd); int main(int argc, char **argv)
{
char * servInetAddr = "127.0.0.1";
int servPort = ;
char buf[MAXLINE];
int connfd;
struct sockaddr_in servaddr; if (argc == ) {
servInetAddr = argv[];
}
if (argc == ) {
servInetAddr = argv[];
servPort = atoi(argv[]);
}
if (argc > ) {
printf("usage: echoclient <IPaddress> <Port>\n");
return -;
} connfd = socket(AF_INET, SOCK_STREAM, ); //bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(servPort);
//inet_pton(AF_INET, servInetAddr, &servaddr.sin_addr);
servaddr.sin_addr.s_addr = inet_addr(servInetAddr);
bzero(&(servaddr.sin_zero), ); if (connect(connfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < ) {
perror("connect error");
return -;
}
printf("welcome to echoclient\n");
handle(connfd); /* do it all */
close(connfd);
printf("exit\n");
exit();
} void handle(int sockfd)
{
char sendline[MAXLINE], recvline[MAXLINE];
int n;
for (;;) {
if (fgets(sendline, MAXLINE, stdin) == NULL)
{
break;//read eof
}
/*
//也可以不用标准库的缓冲流,直接使用系统函数无缓存操作
if (read(STDIN_FILENO, sendline, MAXLINE) == 0) {
break;//read eof
}
*/ n = write(sockfd, sendline, strlen(sendline));
n = read(sockfd, recvline, MAXLINE);
if (n == ) {
printf("echoclient: server terminated prematurely\n");
break;
}
write(STDOUT_FILENO, recvline, n);
//如果用标准库的缓存流输出有时会出现问题
//fputs(recvline, stdout);
}
}
Linux下并发网络设计之I/O复用的更多相关文章
- Linux下TCP网络编程与基于Windows下C#socket编程间通信
一.linux下TCP网络编程基础,需要了解相关函数 Socket():用于套接字初始化. Bind():将 socket 与本机上的一个端口绑定,就可以在该端口监听服务请求. Listen():使s ...
- Linux下的网络远程安装
Linux下的网络远程安装 1.用RHEL6.5光盘安装第一台服务器 2.在第一台服务器上配置YUM服务器 先创建一个挂载 #mount #umount /dev/cdrom #mkdir /mnt/ ...
- Linux高并发网络编程开发——10-Linux系统编程-第10天(网络编程基础-socket)
在学习Linux高并发网络编程开发总结了笔记,并分享出来.有问题请及时联系博主:Alliswell_WP,转载请注明出处. 10-Linux系统编程-第10天(网络编程基础-socket) 在学习Li ...
- 八、Linux下的网络服务器模型
服务器设计技术有很多,按使用的协议来分有TCP服务器和UDP服务器,按处理方式来分有循环服务器和并发服务器. 在网络程序里面,一般来说都是许多客户对应一个服务器,为了处理客户的请求,对服务端的程序就提 ...
- linux下Python网络编程框架-Twisted安装
Twisted是python下的用来进行网络服务和应用程序编程的框架,安装Twisted前需要系统预先安装有python. 一.安装Twisted http://twistedmatrix.com/R ...
- netstat 在windows下和Linux下查看网络连接和端口占用
假设忽然起个服务,告诉我8080端口被占用了,OK,我要去看一下是什么服务正在占用着,能不能杀 先假设我是在Windows下: 第一列: Proto 协议 第二列: 本地地址[ip+端口] 第三列:远 ...
- 从操作系统层面理解Linux下的网络IO模型
I/O( INPUT OUTPUT),包括文件I/O.网络I/O. 计算机世界里的速度鄙视: 内存读数据:纳秒级别. 千兆网卡读数据:微妙级别.1微秒=1000纳秒,网卡比内存慢了千倍. 磁盘读数据: ...
- linux下常用网络操作汇总
首先说明下RHEL6下设置IP地址的确和RHEL5下有几点是不同的. 我装完RHEL6中默认选择的是DHCP自动获取方式: [root@localhost ~]# vi /etc/sysconfig/ ...
- Linux下Socket网络编程
什么是Socket Socket接口是TCP/IP网络的API,Socket接口定义了许多函数或例程,程序员可以用它们来开发TCP/IP网络上的应用程序.要学Internet上的TCP/IP网络编程, ...
随机推荐
- (7) 引用Objective-C class library
原文 引用Objective-C class library 这个范例是如何在Xamarin.ios中去使用一个我们自行在Xcode中开发的Objective-c Class Library. 主要会 ...
- SQLServer2012 和 MariaDB 10.0.3 分页效率的对比
1. 实验环境 R910服务器, 16G内存 SqlServer 2012 64bit MariaDB 10.0.3 64bit (InnoDB) 2. 实验表情况 rtlBill ...
- 2016 Multi-University Training Contest 5&6 总结
第五场和第六场多校都打得很糟糕. 能做到不以物喜不以己悲是假的,这对队伍的情绪也可以算上是比较大的打击. 很多时候我们发现了问题,但是依旧没有采取有效的方法去解决它,甚至也没有尝试去改变.这是一件相当 ...
- C语言 大小端 字节对齐
参考:http://www.cnblogs.com/graphics/archive/2011/04/22/2010662.html 1. 大端序:数据的高位字节存放在地址的低端,低位字节存放在地址的 ...
- html学习笔记一
学习了一天,总结巩固下自己收获. html是超文本标记语言,而不是编程语言. 1:html结构 包含html标签,head标签,title标签,body标签. <html> <hea ...
- C#DataTable DataSet DataRow区别详解
DataSet 是C#中用来存储数据库数据的.其实,它的作用是在内存中模拟数据库.我们现实生活中的数据库从大到小的基本结构类似于:数据库实例,表,列,行.在C#语言中,我们在内存中也模拟出了一个这样的 ...
- ContentType 属性 MIME
".asf" = "video/x-ms-asf" ".avi" = "video/avi" ".doc&qu ...
- jquery ajax 在ie7不能正常使用
jquery ajax结构不规范到时再ie8以下的用户不能正常使用.比如[1,2,].{1,2,},结构内部的最后不能有“,”.
- C学习之结构体
结构体(struct) 结构体是由基本数据类型构成的.并用一个标识符来命名的各种变量的组合,结构体中可以使用不同的数据类型. 1. 结构体说明和结构体变量定义 在Turbo C中, 结构体也是一种数据 ...
- 张孝祥Java高新技术汇总
一.自动装箱和拆箱: 在Java中有8种基本数据类型:byte,short,int,long,float,double,char,boolean.而基本数据类型不是对象,这时人们给他们定义了包装类,使 ...