使用select多路復用技術的非阻塞模型
select多路復用通常具有很好的跨平台性,也能提供不錯的併發效能,但是在通常情況下有最大監聽檔案描述符的限制(通常1024),如果不需要達到c10k這種前端高效能伺服器的要求,採用select+nonblocking的方式能降低程式設計的難度
用到的介面
fd_setsize;
fd_set(<#fd#>, <#fdsetp#>);
fd_isset(<#fd#>, <#fdsetp#>);
fd_zero(<#fdsetp#>);
select(<#(int)__nfds#>, <#(fd_set*)__readfds#>, <#(fd_set*)__writefds#>, <#(fd_set*)__exceptfds#>, <#(struct timeval*)__timeout#>)
//select-nonblocking
#include #include #include #include #include #include #include #include #include #include #define max_read_size 20*1024*1024
#define max_write_size 20*1024*1024
#define max_chunck_size 2*1024*1024
#define keep_alive 0
/* *
* a ****** server using select
* */
void run();
int main(int argc, char *ar**)
//struct for storing read-write buffer
struct fd_state ;
//alloc fd_state
struct fd_state *alloc_fd_state(void)
;//free fd_state pointer
void free_fd_state(struct fd_state *p)
//handle error
void error_exit()
//set sock non-blocking
void made_nonblock(int fd)
}//handle read event
int do_read(int fd,struct fd_state *state)
*/ }
}state->writing = 1;
state->write_upto_len = state->read_len;
//write(1, state->buffer, state->read_len);
//nothing read
if (result==0)
if (result<0)
return 0;
}int do_write(int fd,struct fd_state *state)
state->written_len+=result;
}if (state->written_len==state->read_len)
state->written_len = state->write_upto_len = state->read_len = 0;
state->writing = 0;
if (result<0)
if (result==0)
return 1;
return 0;
}void do_select(int serverfd)
fd_set read_set,write_set,error_set;
fd_zero(&read_set);
fd_zero(&write_set);
fd_zero(&error_set);
//main loop
while(1)
fd_set(i, &read_set);
if (state[i]->writing)}}
if(select(maxfd+1, &read_set, &write_set, &error_set, null)<0)
// if server becomes readable then accept the client sock
// and alloc the client sock state
if(fd_isset(serverfd, &read_set))else if(client> fd_setsize)else
}//handle the fd_set
for (int j = 0; j < maxfd + 1; ++j)
}//handle error
if (flag)}}
}int create_server_socket()
int reuse = 1;
if (setsockopt(serverfd, sol_socket, so_reuseaddr, &reuse, sizeof(reuse))<0)
return serverfd;
}void run()
if(listen(serverfd, 50)<0)
do_select(serverfd);
}
linux 網路程式設計 三 非阻塞通訊select
int select int nfds,fd set readfds,fd set writefds,fd set exceptfds,struct timeval timeout 說明 int maxfdp是乙個整數值,是指集合中所有檔案描述符的範圍,即所有檔案描述符的最大值加1。fd set r...
linux 網路程式設計 三 非阻塞通訊select
int select int nfds,fd set readfds,fd set writefds,fd set exceptfds,struct timeval timeout 說明 int maxfdp是乙個整數值,是指集合中所有檔案描述符的範圍,即所有檔案描述符的最大值加1。fd set r...
Linux網路程式設計之廣播
1.概念 前面介紹的tcp,udp都是單播方式,即一對一.而廣播是一台主機向區域網內的所有主機傳送資料。這時,同一網段的所有主機都能接收到資料。傳送廣播包的步驟大致如下 1 確定乙個傳送廣播的介面,如eth0 2 確定廣播的位址,通過ioctl函式,請求碼設定為siocgifbrdaddr得到廣播的...