int fd_set_nonblock(int fd)
{
int rv;
rv = fcntl(fd, F_GETFL, 0);
if(rv < 0){
printf("fcntl error\n");
return -1;
}
rv = fcntl(fd, F_SETFL, rv | O_NONBLOCK);
if(rv < 0){
printf("fcntl error\n");
return -1;
}
return 0;
}
int init_server_socket()
{
int fd;
struct sockaddr_in addr;
int ret;
int v_on = 1;
fd = socket(PF_INET, SOCK_STREAM, 0);
if (fd < 0) {
printf("server socket create failed\n");
return -1;
}
ret = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &v_on, sizeof (v_on));
if (ret != 0) {
printf("setsockopt error\n");
goto out_close_socket;
}
memset(&addr, 0, sizeof(struct sockaddr_in));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr=INADDR_ANY;
addr.sin_port = htons(40000);
ret = bind(fd,(struct sockaddr *)&addr,sizeof(addr));
if (ret < 0) {
printf("Server socket bind error\n");
goto out_close_socket;
}
ret = listen(fd, 20);
if (ret < 0) {
printf("Server socket listen error\n");
goto out_close_socket;
}
ret = fd_set_nonblock(fd);
if(ret != 0){
printf("fd_set_nonblock() failed\n");
goto out_close_socket;
}
return fd;
out_close_socket:
close(fd);
return -1;
}
int main(int argc, char *argv[])
{
int listenfd;
int rv;
listenfd = init_server_socket();
if (listenfd < 0) {
exit(1);
}
while(1){
fd_set readfds;
struct timeval t;
int connfd;
structsockaddr_in clientaddr;
socklen_t addrlen;
int r;
FD_ZERO(&readfds);
if(listenfd >= 0)FD_SET(listenfd, &readfds);
t.tv_sec = 60;
t.tv_usec = 0;
r = select(listenfd+1, &readfds, NULL, NULL, &t);
if(r == 0){
continue;
}
if(r < 0){
if(errno != EINTR)
printf("signal caught\n");
continue;
}
if(!FD_ISSET(listenfd, &readfds))
continue;
memset(&clientaddr, 0, sizeof(struct sockaddr_in));
addrlen = sizeof(struct sockaddr_in);
connfd = accept(listenfd,(struct sockaddr *)&clientaddr, &addrlen);
if(connfd < 0){
continue;
}
/**********工作线程**********/
}
close(listenfd);
return 0;
}
服务器端编程示例