• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C++ FD_CLR函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C++中FD_CLR函数的典型用法代码示例。如果您正苦于以下问题:C++ FD_CLR函数的具体用法?C++ FD_CLR怎么用?C++ FD_CLR使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了FD_CLR函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: main

int main()
{
	int server_sockfd, client_sockfd;
	int server_len, client_len;
	struct sockaddr_in server_address;
	struct sockaddr_in client_address;
	int result;
	fd_set readfds, testfds;

	server_sockfd = socket(AF_INET, SOCK_STREAM, 0);

	server_address.sin_family = AF_INET;
	server_address.sin_addr.s_addr = INADDR_ANY;
	server_address.sin_port = htons(9734);
	server_len = sizeof(server_address);

	bind(server_sockfd, (struct sockaddr *)&server_address, server_len);
	listen(server_sockfd, 5);

	FD_ZERO(&readfds);
	FD_SET(server_sockfd, &readfds);

	while (1) {
		char ch;
		int fd;
		int nread;

		testfds = readfds;

		printf("server waiting\n");
		result = select(FD_SETSIZE, &testfds, (fd_set *)0,
				        (fd_set *)0, (struct timeval *)0);

		if (result < 1) {
			perror("server5");
			exit(1);
		}

		for (fd = 0; fd < FD_SETSIZE; fd++) {
			if (FD_ISSET(fd, &testfds)) {
				if (fd == server_sockfd) {
					client_len = sizeof(client_address);
					client_sockfd = accept(server_sockfd,
							(struct sockaddr *)&client_address, &client_len);
					FD_SET(client_sockfd, &readfds);
					printf("add client on fd %d\n", client_sockfd);
				} else {
					ioctl(fd, FIONREAD, &nread);

					if (nread == 0) {
						close(fd);
						FD_CLR(fd, &readfds);
						printf("removing client on fd %d\n", fd);
					} else {
						read(fd, &ch, 1);
						sleep(5);
						printf("serving client on fd %d\n", fd);
						ch++;
						write(fd, &ch, 1);
					}
				}
			}
		}
	}
}
开发者ID:chenjianlong,项目名称:books-code,代码行数:65,代码来源:server5.c


示例2: FCPPT_ASSERT


//.........这里部分代码省略.........
		out_pipe[writing_end]);
	close(
		err_pipe[writing_end]);

	fd_set master_fds;
	FD_ZERO(
		&master_fds);
	
	FD_SET(
		out_pipe[reading_end],
		&master_fds);

	FD_SET(
		err_pipe[reading_end],
		&master_fds);

	output out;
	int eof_count = 
		0;
	while (eof_count < 2)
	{
		fd_set read_fds = master_fds;

		int 
			maxfd = 
				std::max(
					out_pipe[reading_end],
					err_pipe[reading_end]),
			select_return = 
				select(
					maxfd+1,
					&read_fds,
					0,
					0,
					0);

		if (select_return == -1)
			throw 
				fcppt::exception(
					FCPPT_TEXT("select failed"));

		int const fds[2] = 
			{ 
				out_pipe[reading_end],
				err_pipe[reading_end] 
			};

		fcppt::string *outs[2] = 
			{
				&out.out,
				&out.err
			};
		for (int i = 0; i < 2; ++i)
		{
			if (!FD_ISSET(fds[i],&read_fds))
				continue;

			ssize_t const buffer_size = 
				static_cast<ssize_t>(
					1024);

			char char_buffer[buffer_size];

			ssize_t const b = ::read(
				fds[i],
				char_buffer,
				static_cast<std::size_t>(
					buffer_size-1));
			
			if (b == static_cast<ssize_t>(0))
			{
	//			fcppt::io::cerr << "recieved eof on fd " << fds[i] << "\n";
				eof_count++;
				FD_CLR(
					fds[i],
					&master_fds);
				continue;
			}
			
			if (b == static_cast<ssize_t>(-1))
				throw 
					fcppt::exception(
						FCPPT_TEXT("read failed"));

	//		fcppt::io::cerr << "received the following crap: " << fcppt::string(char_buffer,char_buffer+b) << "\n";

			outs[i]->insert(
				outs[i]->end(),
				char_buffer,
				char_buffer + b);
		}
	}
	
	waitpid(
		pid,
		(&out.exit_code),
		0);
	
	return out;
}
开发者ID:freundlich,项目名称:gitbot,代码行数:101,代码来源:call.cpp


示例3: relay_tcp

void relay_tcp(SOCKS_STATE *state)
{
  fd_set   rfds, xfds;
  int      nfds, sfd;
  struct   timeval tv;
  struct   timezone tz;
  ssize_t  wc;
  rlyinfo  ri;
  int      done;
  u_long   max_count = idle_timeout;
  u_long   timeout_count;
  LOGINFO	li;

  memset(&ri, 0, sizeof(ri));
  memset(&li, 0, sizeof(li));
  ri.ss = (struct sockaddr *)NULL;
  ri.len = 0;
  ri.nr = BUFSIZE;

  nfds = MAX(state->r, state->s);
  setsignal(SIGALRM, timeout);
  gettimeofday(&li.start, &tz);
  li.bc = li.upl = li.dnl = 0;
  ri.flags = 0; timeout_count = 0;
  for (;;) {
    FD_ZERO(&rfds);
    FD_SET(state->s, &rfds); FD_SET(state->r, &rfds);
    if (ri.flags == 0) {
      FD_ZERO(&xfds);
      FD_SET(state->s, &xfds); FD_SET(state->r, &xfds);
    }
    done = 0;
    /* idle timeout related setting. */
    tv.tv_sec = 60; tv.tv_usec = 0;   /* unit = 1 minute. */
    tz.tz_minuteswest = 0; tz.tz_dsttime = 0;
    sfd = select(nfds+1, &rfds, 0, &xfds, &tv);
    if (sfd > 0) {
      if (FD_ISSET(state->r, &rfds)) {
	ri.from = state->r; ri.to = state->s; ri.flags = 0;
	if ((wc = forward(&ri)) <= 0)
	  done++;
	else
	  li.bc += wc; li.dnl += wc;

	FD_CLR(state->r, &rfds);
      }
      if (FD_ISSET(state->r, &xfds)) {
	ri.from = state->r; ri.to = state->s; ri.flags = MSG_OOB;
	if ((wc = forward(&ri)) <= 0)
	  done++;
	else
	  li.bc += wc; li.dnl += wc;
	FD_CLR(state->r, &xfds);
      }
      if (FD_ISSET(state->s, &rfds)) {
	ri.from = state->s; ri.to = state->r; ri.flags = 0;
	if ((wc = forward(&ri)) <= 0)
	  done++;
	else
	  li.bc += wc; li.upl += wc;
	FD_CLR(state->s, &rfds);
      }
      if (FD_ISSET(state->s, &xfds)) {
	ri.from = state->s; ri.to = state->r; ri.flags = MSG_OOB;
	if ((wc = forward(&ri)) <= 0)
	  done++;
	else
	  li.bc += wc; li.upl += wc;
	FD_CLR(state->s, &xfds);
      }
      if (done > 0)
	break;
    } else if (sfd < 0) {
      if (errno != EINTR)
	break;
    } else { /* sfd == 0 */
      if (max_count != 0) {
	timeout_count++;
	if (timeout_count > max_count)
	  break;
      }
    }
  }
  gettimeofday(&li.end, &tz);
  log_transfer(state->si, &li);

  close(state->r);
  close(state->s);
}
开发者ID:CRDevOps,项目名称:srelay,代码行数:89,代码来源:relay.c


示例4: main

/**
 * new connecion comes, copy file descroptor of new connecton to child
 * process , parent process select
 * @return  0
 */
int main(int argc, char **argv)
{

    int res;
    res = register_sig_handler();
    if (res < 0)
        err_sys("register_sig_handler is err");

    my_getopt(argc, argv);

    int pipefd[2];

    int socket_fd;
    res = srv_socket_init(&socket_fd, 50, PORT);
    if (res < 0)
        err_sys("srv_socket_init err");

    fd_set myset;
    FD_ZERO(&myset);
    FD_SET(socket_fd, &myset);
    int max = socket_fd;

    arraychild = (child_t *) malloc(sizeof(child_t) * childnum);
    memset(arraychild, 0, sizeof(child_t) * childnum);
    for (int i = 0 ; i < childnum; i++)
    {

        res = socketpair(AF_LOCAL, SOCK_STREAM, 0, pipefd);
        if (res < 0)
            err_sys("socketpair is err");
        arraychild[i].child_pipefd = pipefd[0];
        FD_SET(pipefd[0], &myset);
        if (pipefd[0] > max)
            max = pipefd[0];

        int pid = fork();
        if (pid < 0)
            err_sys("fork err");

        if (pid == 0)
        {
            srv_socket_destory(&socket_fd);

            int connfd;
            int childpid = getpid();
            while(1)
            {

                char c;
                res = read_fd(pipefd[1], &c, 1, &connfd);
                if (res < 0)
                    err_sys("read_fd err");
                fprintf(stdout, "pid is %d, accept success.\n",childpid);
                child_process(connfd);

                write(pipefd[1], "", 1);

                srv_socket_close(&connfd);
            }
            //exit(0);
        }
        else
        {
            arraychild[i].child_pid = pid;
        }
    }

    struct sigaction myact;
    myact.sa_handler = sig_int_handler;
    if (sigaction(SIGINT, &myact, NULL) < 0)
        err_sys("sigaction err");

    int navail = childnum;
    fd_set rset ;
    int newfd;
    int i = 0;
    while(1)
    {
        rset = myset;
        if (navail <=0 )
            FD_CLR(socket_fd, &rset);


        select(max + 1, &rset, NULL, NULL, NULL);
        if (FD_ISSET(socket_fd, &rset))
        {
            newfd = accept(socket_fd, NULL, NULL);

            for (i = 0; i < childnum; i++)
            {
                if (arraychild[i].child_status == 0)
                    break;
            }

            res = write_fd(arraychild[i].child_pipefd, "", 1, newfd);
//.........这里部分代码省略.........
开发者ID:fonglee,项目名称:just_for_fun,代码行数:101,代码来源:server4.c


示例5: main


//.........这里部分代码省略.........
                if  ( FD_ISSET ( i,  &ler_fds))  { 
                    
                    if ( i == clientes_fd[0]) {
                     
                        //trata novas conexões
                       client_addr_size = sizeof(client_addr);
                        
                        if (( novofd = accept(fd,(struct sockaddr *)&client_addr, &client_addr_size)) == -1)  {
                            perror ("accept");
                        } else {
                            FD_SET ( novofd , &master);//adiciona ao mestre
                            char print[150]="->";
							char t[5];
							
							strcat(print,"servidor : nova conexão de ");
							strcat(print, inet_ntoa(client_addr.sin_addr));
							strcat(print," no  socket ");
							sprintf(t, "%d", novofd);
							strcat(print, t);
							strcat(print, "\n");
							
							for (j = 0; j<MAX; j++)  {
                                
                                //envia a todos os clientes
                                if (FD_ISSET (j, &master)) {
                                    // exceto a nós e ao socket em escuta
                                  
                                    if (j != fd &&j != novofd) {
                                         if (write(j,print,strlen(print)) == -1) {
                                        perror ("write");
                                       
                            }}}}
                            print[0]='\0';
                            
                            if(fdmax<novofd){
								fdmax=novofd;
								novofd=0;
							}
							clientes_fd[coloca_array(clientes_fd)]=novofd;
							
                        
                    }} else {

                        // cuida dos dados do cliente
                      
                           if  ( (nbytes=(read (i, buffer, BUF_SIZE-1)))>= 0) {
                            
                            // recebeu erro ou a conexão foifechada pelo cliente
                            if (nbytes == 0) {
								char printR[150]="->";
								char p[5];
								strcat(printR," servidor : o Cliente foi desligado ");
								strcat(printR, inet_ntoa(client_addr.sin_addr));
								strcat(printR," no  socket ");
								sprintf(p, "%d", i);
								strcat(printR, p);
								strcat(printR, "\n");
							
								for (j = 0; j<MAX; j++)  {
                                
                                //envia a todos os clientes
									if (FD_ISSET (j, &master)) {
                                    // menos aos nós e ao socket em escuta
                                  
										if (j != fd &&j != novofd) {
											if (write(j,printR,strlen(printR)) == -1) {
											perror ("write");
                                       
                            }}}}
                            printR[0]='\0';
                                FD_CLR( i , &master); // clear do conjunto mestre
                                search(clientes_fd, i);
                            } else if(nbytes==-1) {
                                perror ("read"); 
                            }
                           
                        }
                            // temos alguns dados do cliente
                            for (j = 0; j<MAX; j++)  {
                                
                                //envia a todos os clientes
                                if (FD_ISSET (j, &master)) {
                                    // exceto a nós e ao socket em escuta
                                  
                                    if (j != fd &&j!=i ) {
                                         if (write(j,buffer,nbytes) == -1) {
                                        perror ("write");
                                         }
                                    }
                                }
                            }
                        }
                    } 
                }
            }
       
    
  
  return 0;
}
开发者ID:BrunoMadWork,项目名称:Universidade,代码行数:101,代码来源:server.c


示例6: irc_perform


//.........这里部分代码省略.........
        int callval_i;
        int connect_error;
        SIGNEDSOCK int connect_error_len = sizeof(connect_error);
        SIGNEDSOCK int addrlen;

        callval_i = getsockopt(gnetwork->ircserver,
                               SOL_SOCKET, SO_ERROR,
                               &connect_error, &connect_error_len);

        if (callval_i < 0) {
          outerror(OUTERROR_TYPE_WARN,
                   "Couldn't determine connection status: %s on %s",
                   strerror(errno), gnetwork->name);
          close_server();
          continue;
        }
        if (connect_error) {
          ioutput(OUT_S|OUT_L|OUT_D, COLOR_NO_COLOR,
                  "Server Connection Failed: %s on %s", strerror(connect_error), gnetwork->name);
          close_server();
          continue;
        }

        ioutput(OUT_S|OUT_L|OUT_D, COLOR_NO_COLOR,
                "Server Connection to %s Established, Logging In",  gnetwork->name);
        gnetwork->serverstatus = SERVERSTATUS_CONNECTED;
        gnetwork->connecttime = gdata.curtime;
        gnetwork->botstatus = BOTSTATUS_LOGIN;
        ch = irlist_get_head(&(gnetwork->channels));
        if (ch == NULL) {
          gnetwork->botstatus = BOTSTATUS_JOINED;
          start_sends();
        }
        FD_CLR(gnetwork->ircserver, &gdata.writeset);

        addrlen = sizeof(gnetwork->myip);
        bzero((char *) &(gnetwork->myip), sizeof(gnetwork->myip));
        if (getsockname(gnetwork->ircserver, &(gnetwork->myip.sa), &addrlen) >= 0) {
          if (gdata.debug > 0) {
            char *msg;
            msg = mymalloc(maxtextlength);
            my_getnameinfo(msg, maxtextlength -1, &(gnetwork->myip.sa));
            ioutput(OUT_S, COLOR_YELLOW, "using %s", msg);
            mydelete(msg);
          }
          if (!gnetwork->usenatip) {
            gnetwork->ourip = ntohl(gnetwork->myip.sin.sin_addr.s_addr);
            if (gdata.debug > 0) {
              ioutput(OUT_S, COLOR_YELLOW, "ourip = " IPV4_PRINT_FMT,
                      IPV4_PRINT_DATA(gnetwork->ourip));
            }
          }
        } else {
          outerror(OUTERROR_TYPE_WARN, "couldn't get ourip on %s", gnetwork->name);
        }

        handshake_ssl();
      }
      if (changesec)
        irc_server_timeout();
      continue;
    }

    if (gnetwork->serverstatus == SERVERSTATUS_RESOLVING) {
      if (FD_ISSET(gnetwork->serv_resolv.sp_fd[0], &gdata.readset)) {
        res_addrinfo_t remote;
开发者ID:optix2000,项目名称:debian-iroffer-dinoex,代码行数:67,代码来源:dinoex_irc.c


示例7: main

int main(int argc,char *argv[]){
	int i,fd,nmaxconn,nfiles,maxfd,nconn,flags;
	char buf[MAXLINE];
	fd_set rs,ws;

	if(argc < 4)
		err_quit("usage : web <#conn> hostname homepage file1 ...");
	nmaxconn = atoi(argv[1]);

	nfiles = min(argc-4,MAXFILES);

	for(i=0;i<nfiles;i++){
		file[i].f_name = argv[4+i];
		file[i].f_host = argv[2];
		file[i].flags = 0;
	}
	home_page(argv[2],argv[3]);

	FD_ZERO(&rs);
	FD_ZERO(&ws);
	maxfd = -1;
	nconn = 0;
	nleftconn = nlefttoread = nfiles;

	while(nlefttoread > 0){
		while(nconn < nmaxconn && nleftconn > 0){
			for(i=0;i<nfiles;i++)
				if(file[i].flags != 0)
					break;
			if(i == nfiles)
				err_quit("nleftconn = %d but nothing found\n",nleftconn);
			start_connect(&file[i]);
			nconn++;
			nleftconn--;
		}
		rs = rset;
		ws = wset;
		Select(maxfd+1,&rset,&wset,NULL,NULL);
		
		for(i=0;i<nfiles;i++){
			flags = file[i].flags;
			if(flags == 0 || flags == F_DONE)
				continue;
			fd = file[i].f_fd;
			if(flags &  F_CONNECTING && (FD_ISSET(fd,&rset) || FD_ISSET(fd,&wset))){
				n=sizeof(error);
				if(getsockopt(fd,SOL_SOCKET,SO_ERROR,&error,&n) < 0 || error != 0)
					err_ret("nonblocking connect failed for %s\n",file[i].f_name);
				printf("connection established for %s\n",file[i].f_name);
				FD_CLR(fd,&wset);
				write_get_cmd(&file[i]);
			}else if(flags & F_READING && FD_ISSET(fd,&rset)){
				if((n = nread(fd,buf,sizeof(buf))) == 0){
					printf("end-of-file on %s\n",file[i].f_name);
					Close(fd);
					file[i].flags = F_DONE;
					FD_CLR(fd,&rset);
					nconn--;
					nlefconn--;
					nlefttoread--;
				}else {
					printf("read %d bytes from %s\n",n,file[i].f_name);
				}
			}
		}
	}
	exit(0);
}
开发者ID:hu010354,项目名称:kaizer,代码行数:68,代码来源:web.c


示例8: callmgr_main

/*** Call Manager *************************************************************/
int callmgr_main(int argc, char **argv, char **envp)
{
    struct in_addr inetaddr;
    int inet_sock, unix_sock;
    fd_set call_set;
    PPTP_CONN * conn;
    VECTOR * call_list;
    int max_fd = 0;
    volatile int first = 1;
    int retval;
    int i;
    char * volatile phonenr;
    /* Step 0: Check arguments */
    if (argc < 2) 
        fatal("Usage: %s ip.add.ress.here [--phone <phone number>]", argv[0]);
    phonenr = argc == 3 ? argv[2] : NULL;
    if (inet_aton(argv[1], &inetaddr) == 0)
        fatal("Invalid IP address: %s", argv[1]);
    routing_init(inet_ntoa(inetaddr));
    routing_start();
    /* Step 1: Open sockets. */
    if ((inet_sock = open_inetsock(inetaddr)) < 0)
        fatal("Could not open control connection to %s", argv[1]);
    if ((unix_sock = open_unixsock(inetaddr)) < 0)
        fatal("Could not open unix socket for %s", argv[1]);
    /* Step 1b: FORK and return status to calling process. */
    switch (fork()) {
        case 0: /* child. stick around. */
            break;
        case -1: /* failure.  Fatal. */
            fatal("Could not fork.");
        default: /* Parent. Return status to caller. */
            exit(0);
    }
    /* re-open stderr as /dev/null to release it */
    file2fd("/dev/null", "wb", STDERR_FILENO);
    /* Step 1c: Clean up unix socket on TERM */
    if (sigsetjmp(callmgr_env, 1) != 0)
        goto cleanup;
    signal(SIGINT, callmgr_sighandler);
    signal(SIGTERM, callmgr_sighandler);
    signal(SIGPIPE, callmgr_do_nothing);
    signal(SIGUSR1, callmgr_do_nothing); /* signal state change
                                            wake up accept */
    /* Step 2: Open control connection and register callback */
    if ((conn = pptp_conn_open(inet_sock, 1, NULL/* callback */)) == NULL) {
        close(unix_sock); close(inet_sock); fatal("Could not open connection.");
    }
    FD_ZERO(&call_set);
    call_list = vector_create();
    { 
        struct local_conninfo *conninfo = malloc(sizeof(*conninfo));
        if (conninfo == NULL) {
            close(unix_sock); close(inet_sock); fatal("No memory.");
        }
        conninfo->call_list = call_list;
        conninfo->call_set  = &call_set;
        pptp_conn_closure_put(conn, conninfo);
    }
    if (sigsetjmp(callmgr_env, 1) != 0) goto shutdown;
    /* Step 3: Get FD_SETs */
    max_fd = unix_sock;
    do {
        int rc;
        fd_set read_set = call_set, write_set;
        FD_ZERO (&write_set);
        if (pptp_conn_established(conn)) {
	  FD_SET (unix_sock, &read_set);
	  if (unix_sock > max_fd) max_fd = unix_sock;
	}
        pptp_fd_set(conn, &read_set, &write_set, &max_fd);
        for (; max_fd > 0 ; max_fd--) {
            if (FD_ISSET (max_fd, &read_set) ||
                    FD_ISSET (max_fd, &write_set))
                break;
        }
        /* Step 4: Wait on INET or UNIX event */
        if ((rc = select(max_fd + 1, &read_set, &write_set, NULL, NULL)) <0) {
	  if (errno == EBADF) break;
	  /* a signal or somesuch. */
	  continue;
	}
        /* Step 5a: Handle INET events */
        rc = pptp_dispatch(conn, &read_set, &write_set);
	if (rc < 0)
	    break;
        /* Step 5b: Handle new connection to UNIX socket */
        if (FD_ISSET(unix_sock, &read_set)) {
            /* New call! */
            struct sockaddr_un from;
            socklen_t len = sizeof(from);
            PPTP_CALL * call;
            struct local_callinfo *lci;
            int s;
            /* Accept the socket */
            FD_CLR (unix_sock, &read_set);
            if ((s = accept(unix_sock, (struct sockaddr *) &from, &len)) < 0) {
                warn("Socket not accepted: %s", strerror(errno));
                goto skip_accept;
//.........这里部分代码省略.........
开发者ID:WiseMan787,项目名称:ralink_sdk,代码行数:101,代码来源:pptp_callmgr.c


示例9: main

int main(int argc, char* argv[])
{

    int i , maxi , maxfd , listenfd , connfd , sockfd ;
    int nready , client[ FD_SETSIZE ] ;
    ssize_t n ;
    fd_set rset , allset ;
    char buf [ MAXLINE ];
    socklen_t clilen ;
    struct sockaddr_in cliaddr , servaddr ;

		//creat socket
    listenfd = socket( AF_INET , SOCK_STREAM , 0 );
		//set socket
    bzero(&servaddr , sizeof( servaddr ));
    servaddr.sin_family = AF_INET ;
    servaddr.sin_addr.s_addr = htonl( INADDR_ANY );
    servaddr.sin_port = htons( SERV_PORT ) ;
		//bind port
    bind(listenfd , (SA*) &servaddr ,sizeof(servaddr) );
		//listen port listenfd
    listen(listenfd , 10 );  // max client is 10
		//consider maxfd 
    maxfd = listenfd ;
    //initial maxi which is num of fd
		maxi = -1;
		//all client port is closed now
    for(i = 0; i < FD_SETSIZE ; i++) client[i] = -1 ;
    
		//initial select set
		FD_ZERO(&allset);
		//wait listenfd which is in allset when select
    FD_SET(listenfd , &allset );

    printf("ready to wait \n listenfd=%d",listenfd);

    for(;;)
    {
        rset = allset ;
				//nready is the fd ready to ready
        nready = select( maxfd + 1 , &rset , NULL , NULL , NULL );

        if(FD_ISSET(listenfd , &rset) ){
						//connect to ready client
            clilen = sizeof( cliaddr ) ;
            connfd = accept( listenfd , (SA* )&cliaddr , &clilen );

            printf("start to read: \n");
						//sav fd to client[i]
            for(i = 0 ; i<FD_SETSIZE; i++){
                if(client[i]<0) {
                    client[i] = connfd;
                    break;
                }
						}
            //if full, exit
						if(i == FD_SETSIZE){
                printf("too many client\n");
                exit(0);
            }
						//wait connfd when select
            FD_SET(connfd, &allset);
            if(connfd > maxfd )maxfd = connfd;
            if(i > maxi )maxi = i;
            if(--nready <= 0)continue;
        }
				//seek connected socket
				for(i=0;i<=maxi;i++){
            if( (sockfd = client[i]) < 0 )continue;
            if(FD_ISSET(sockfd,&rset)){
                if((n = readline(sockfd , buf , MAXLINE )) == 0 )
                {
                    close(sockfd);
                    FD_CLR(sockfd , &allset );
                    client[i] = -1;
                }
                else if(n>0){
									int k;
									//write messege to all client
									printf("%s",buf);
									for(k=0;k<=maxi;k++){
										if(client[k]!=-1){
											printf("write in k=%d\n",k);
											if((write(client[k] , buf , n))!=n)printf("write error!\n");
										}
									}
                }
								else if (n<0)printf("error!\n");	
								if(--nready <= 0) break;
            }

        }

    }


}
开发者ID:baldureyes,项目名称:np,代码行数:97,代码来源:server.c


示例10: main

int
main(int argc, char ** argv)
{
    int listenfd, connfd, i, maxindex;
    int n, nready;
    int client[MAXCLIENT];
    fd_set rset;
    int maxfds;
    char buf[MAXLINE];
    struct sockaddr_in svraddr, cliaddr;
    svraddr.sin_family = AF_INET;
    svraddr.sin_port = htons(SEVR_PORT);
    svraddr.sin_addr.s_addr = htonl(INADDR_ANY);

    listenfd = socket(AF_INET, SOCK_STREAM, 0);
    Bind(listenfd, (struct sockaddr *)&svraddr, sizeof(svraddr));
    Listen(listenfd, 17);
    Signal(SIGCHLD, sig_child);
    FD_ZERO(&rset);
    maxfds = listenfd + 1;
    socklen_t clilen = sizeof(cliaddr);

    for(i=0; i<MAXCLIENT; i++)
        client[i] = -1;
    maxindex = 0;
    for(;;)
    {
        FD_SET(listenfd, &rset);
        nready = Select(maxfds, &rset, NULL, NULL, NULL);
        if( FD_ISSET(listenfd, &rset) )
        {
            connfd = Accept(listenfd, (struct sockaddr *)&cliaddr, &clilen);
            printf("Accept Connection from %s %d\n", inet_ntop(AF_INET, &cliaddr.sin_addr, buf, sizeof(cliaddr)), ntohs(cliaddr.sin_port));
            maxfds = MAX(maxfds, connfd) + 1;
            for(i=0; i<MAXCLIENT; i++)
            {
                if( client[i] < 0 )
                {
                    client[i] = connfd;
                    break;
                }
            }
            if( i == MAXCLIENT )
                err_quit("too many clients");
            FD_SET(connfd, &rset);
            maxfds = MAX(maxfds, connfd) + 1;
            maxindex = MAX(maxindex, i);   //record max index of client valid
        }

        for(i=0; i<maxindex; i++)
        {
            int sockfd;
            if( (sockfd = client[i]) < 0 )    //find valid socket fd
                continue;

            printf("sockfd = %d\n", sockfd);
            if( FD_ISSET(sockfd, &rset) )
            {
                printf("client FD_ISSET\n");
                if( (n = read(sockfd, buf, MAXLINE)) == 0 ) // read EOF
                {
                     close(sockfd);
                     FD_CLR(sockfd, &rset);
                     client[i] = -1;
                }
                else
                    writen(sockfd, buf, n);
            }
            if( -- nready == 0 )
                break;  //process all readable socket fd
        }
    }

}
开发者ID:hnutank163,项目名称:unplearn,代码行数:74,代码来源:echosvr.c


示例11: main

int main() {
    fd_set master;
    fd_set read_fds;
    struct sockaddr_in serveraddr;
    struct sockaddr_in clientaddr;
    int fdmax;
    int listener;
    int newfd;
    char buf[5000];
    int nbytes;
    int yes = 1;
    int addrlen;
    int i, j;

    FD_ZERO(&master);
    FD_ZERO(&read_fds);

    if((listener = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
      perror("Server-socket() error ");
      exit(1);
    }

    printf("Server-socket() is OK...\n");

    serveraddr.sin_family = AF_INET;
    serveraddr.sin_addr.s_addr = INADDR_ANY;
    serveraddr.sin_port = htons(PORT);

    memset(&(serveraddr.sin_zero), '\0', 8);

    if(bind(listener, (struct sockaddr *)&serveraddr, sizeof(serveraddr)) == -1) {
        perror("Server-bind() error ");
        exit(1);
    }

    printf("Server-bind() is OK...\n");

    if(listen(listener, 1000) == -1) {
         perror("Server-listen() error ");
         exit(1);
    }

    printf("Server-listen() is OK...\n");

    FD_SET(listener, &master);
    fdmax = listener;
    for(;;) {
        read_fds = master;
        if(select(fdmax+1, &read_fds, NULL, NULL, NULL) == -1) {
            perror("Server-select() error lol!");
            exit(1);
        }
        else {
          printf("Server-select() is OK...\n");
        }

        for(i = 0; i <= fdmax; i++) {
          if(FD_ISSET(i, &read_fds)) {
                if(i == listener) {
                    addrlen = sizeof(clientaddr);
                    if((newfd = accept(listener, (struct sockaddr *)&clientaddr, &addrlen)) == -1) {
                        perror("Server-accept() error");
                      }
                    else {
                        printf("Server-accept() is OK...\n");
                        FD_SET(newfd, &master);
                        if(newfd > fdmax) {
                            fdmax = newfd;
                        }

                        printf("%s: New connection on socket %d\n", inet_ntoa(clientaddr.sin_addr), newfd);
                    }
                }

                else {
                    if((nbytes = recv(i, buf, sizeof(buf), 0)) <= 0) {
                            if(nbytes == 0)
                                printf("socket %d hung up\n", i);
                            else
                                perror("recv() error");
                            close(i);
                            FD_CLR(i, &master);
                    }
                    else {
                        for(j = 0; j <= fdmax; j++) {
                            if(FD_ISSET(j, &master)) {
                                if(j != listener && j != i) {
                                    if(send(j, buf, nbytes, 0) == -1)
                                        perror("send() error");
                                }
                            }
                        }
                    }
                }
          }
      }
  }
  return 0;
}
开发者ID:mitcse,项目名称:CSE-Labs,代码行数:99,代码来源:groupchatserver.c


示例12: main


//.........这里部分代码省略.........
            if (fcntl(new_fd, F_SETFL, O_NONBLOCK) < 0 ) {
#else
                if(ioctlsocket(new_fd, FIONBIO, &param) < 0){
#endif                
                    SET_ERRNO();
                    print_err(LOG_ERR, "fd%d: Failed to set nonblock: %s (%d)\n",
                              new_fd,strerror(errno),errno);
                    return(-1);
                }
                continue;
            }

            for( rconn = conn_stat_head->next ; rconn != NULL ; rconn = rconn->next){
                int rfd, wfd;

                rfd = rconn->fd;
            
                if (FD_ISSET(rfd, &fdset)){
                    int   rsize;
                    char  databuf[SOCKBUFSIZE];
                    char *bufp;
                    int   datalen;

                    bufp = (char *)databuf;
                    rsize = recv(rfd, bufp, SOCKBUFSIZE,0);
                    if(rsize == 0){
                        /*
                         * コネクションが切断されたようだ。
                         * socket を close してループを抜ける
                         */
                        print_err(LOG_ERR,"fd%d: Connection closed by %s\n", rfd, inet_ntoa(rconn->addr));
                        CLOSE(rfd);
                        print_err(LOG_ERR,"fd%d: closed\n", rfd);
                        FD_CLR(rfd, &fdset_saved);
                        delete_conn_stat(rfd);
                        break;
                    }
                    if(rsize < 0){
                        SET_ERRNO();                    
                        /*
                         * 致命的でない error の場合は無視してループを継続
                         */
                        if(errno == EINTR || errno == EWOULDBLOCK){
                            print_err(LOG_NOTICE, "fd%d: recv: %s\n", rfd, strerror(errno));
                            continue;
                        }
                        /*
                         * エラーが発生したようだ。
                         * socket を close して forループを抜ける
                         */
                        print_err(LOG_ERR,"fd%d: recv: %s\n", rfd,strerror(errno));
                        CLOSE(rfd);
                        print_err(LOG_ERR,"fd%d: closed\n", rfd);
                        FD_CLR(rfd, &fdset_saved);
                        delete_conn_stat(rfd);
                        break;
                    }
                    /*
                     * 他の仮想 NIC にパケットを転送する。
                     * 「待ち」が発生すると、パフォーマンスに影響があるので、EWOULDBLOCK
                     *  の場合は配送をあきらめる。
                     */
                    for(wconn = conn_stat_head->next ; wconn != NULL ; wconn = wconn->next){
                    
                        wfd = wconn->fd;
开发者ID:kaizawa,项目名称:vpn-ste-win,代码行数:66,代码来源:stehub.c


示例13: APR_DECLARE

APR_DECLARE(apr_status_t) apr_pollset_remove(apr_pollset_t *pollset,
                                             const apr_pollfd_t *descriptor)
{
    apr_uint32_t i;
#ifndef HAVE_POLL
    apr_os_sock_t fd;
#endif

#ifdef HAVE_POLL
    for (i = 0; i < pollset->nelts; i++) {
        if (descriptor->desc.s == pollset->query_set[i].desc.s) {
            /* Found an instance of the fd: remove this and any other copies */
            apr_uint32_t dst = i;
            apr_uint32_t old_nelts = pollset->nelts;
            pollset->nelts--;
            for (i++; i < old_nelts; i++) {
                if (descriptor->desc.s == pollset->query_set[i].desc.s) {
                    pollset->nelts--;
                }
                else {
                    pollset->pollset[dst] = pollset->pollset[i];
                    pollset->query_set[dst] = pollset->query_set[i];
                    dst++;
                }
            }
            return APR_SUCCESS;
        }
    }

#else /* no poll */
    if (descriptor->desc_type == APR_POLL_SOCKET) {
        fd = descriptor->desc.s->socketdes;
    }
    else {
#if !APR_FILES_AS_SOCKETS
        return APR_EBADF;
#else
        fd = descriptor->desc.f->filedes;
#endif
    }

    for (i = 0; i < pollset->nelts; i++) {
        if (descriptor->desc.s == pollset->query_set[i].desc.s) {
            /* Found an instance of the fd: remove this and any other copies */
            apr_uint32_t dst = i;
            apr_uint32_t old_nelts = pollset->nelts;
            pollset->nelts--;
            for (i++; i < old_nelts; i++) {
                if (descriptor->desc.s == pollset->query_set[i].desc.s) {
                    pollset->nelts--;
                }
                else {
                    pollset->query_set[dst] = pollset->query_set[i];
                    dst++;
                }
            }
            FD_CLR(fd, &(pollset->readset));
            FD_CLR(fd, &(pollset->writeset));
            FD_CLR(fd, &(pollset->exceptset));
            if (((int)fd == pollset->maxfd) && (pollset->maxfd > 0)) {
                pollset->maxfd--;
            }
            return APR_SUCCESS;
        }
    }
#endif /* no poll */

    return APR_NOTFOUND;
}
开发者ID:Garridon,项目名称:windowsrtdev,代码行数:69,代码来源:poll.c


示例14: main

int main()
{
    struct sockaddr_in name;
    int                s;
    fd_set             mask;
    int                recv_s[10];
    int                valid[10];  
    fd_set             dummy_mask,temp_mask;
    int                i,j,num;
    int                mess_len;
    int                neto_len;
    char               mess_buf[MAX_MESS_LEN];
    long               on=1;

    s = socket(AF_INET, SOCK_STREAM, 0);
    if (s<0) {
        perror("Net_server: socket");
        exit(1);
    }

    if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(on)) < 0)
    {
        perror("Net_server: setsockopt error \n");
        exit(1);
    }

    name.sin_family = AF_INET;
    name.sin_addr.s_addr = INADDR_ANY;
    name.sin_port = htons(PORT);

    if ( bind( s, (struct sockaddr *)&name, sizeof(name) ) < 0 ) {
        perror("Net_server: bind");
        exit(1);
    }
 
    if (listen(s, 4) < 0) {
        perror("Net_server: listen");
        exit(1);
    }

    i = 0;
    int is_first = 0;
    int no_reception = 0;
    FILE * fw;
    struct timeval first, last;
    gettimeofday(&first, NULL);
    int total_bytes=0;
    FD_ZERO(&mask);
    FD_ZERO(&dummy_mask);
    FD_SET(s,&mask);
    for(;;)
    {
        temp_mask = mask;
        num = select( FD_SETSIZE, &temp_mask, &dummy_mask, &dummy_mask, NULL);
        if (num > 0) {
            if ( FD_ISSET(s,&temp_mask) ) {
                recv_s[i] = accept(s, 0, 0) ;
                FD_SET(recv_s[i], &mask);
                valid[i] = 1;
                i++;
            }
            for(j=0; j<i ; j++)
            {   if (valid[j]) {   
                if ( FD_ISSET(recv_s[j],&temp_mask) ) {
                    if (is_first == 0) {
                     is_first = 1;
                     int length;
                     if (recv(recv_s[j], &length, sizeof(length),0) > 0)                     {
                      int strlen = length - sizeof(length);
                      recv(recv_s[j], mess_buf, strlen, 0);
                      mess_buf[strlen] = '\0';
                      printf("Writing to %s\n", mess_buf);
                      gettimeofday(&first, NULL);
                      fw = fopen(mess_buf, "w");
                     }
                    }
                    int len = recv(recv_s[j],mess_buf,MAX_MESS_LEN,0);
                    if( len > 0) {
                        no_reception = 0;
                        fwrite(mess_buf, 1, len, fw);
                        total_bytes = total_bytes + len;
                     }
                      else {
                        no_reception++;
                        if (no_reception == 2) {
                          FD_CLR(recv_s[j], &mask);
                          close(recv_s[j]);
                          valid[j]=0;
                          if (fw != NULL) {
                            fclose(fw);
                          }
                          gettimeofday(&last, NULL);
                          double difference = (double)(last.tv_sec - first.tv_sec) + (double)(last.tv_usec - first.tv_usec) / 1000000.0;
                          double total = (double)total_bytes / 1000000.0;
                          printf("Transfer completed. Total Megabytes %f. Total Time %f. Average Rate (Mbits/sec) %f.\n", total, difference, (total*8.0) / difference);
                          exit(1);
                         }
                      }
                  }
               }
//.........这里部分代码省略.........
开发者ID:zpainesabin,项目名称:distex1,代码行数:101,代码来源:net_server.c


示例15: main

int main(){
	//создаем именованные каналы в ядре с местом в файловом пространстве имен
	printf("Создаю именованные каналы...");fflush(stdout);
	const char *pipe_in="in.fifo", *pipe_out="out.fifo";
	unlink(pipe_in);
	unlink(pipe_out);
	int res=mkfifo(pipe_in,0666);
	if(-1==res){
		perror("Ошибка создания канала in");
		return 1;
	}
	res=mkfifo(pipe_out,0666);
	if(-1==res){
		perror("Ошибка создания канала out");
		return 2;
	}
	printf("ok!\n");

	//получаем файловые дескрипторы каналов и переводим в неблокирующий режим (чтение и запись, чтоб не блокировалось здесь же сразу)
	printf("Получаю файловые дескрипторы...");
	int fd_in=open(pipe_in,O_RDWR|O_NONBLOCK);
	if(-1==fd_in){
		perror("Не получен дескриптор in");
		return 3;
	}
	int fd_out=open(pipe_out,O_RDWR|O_NONBLOCK);
	if(-1==fd_out){
		perror("Не получен дескриптор out");
		close(fd_in);
		return 4;
	}
	printf("ok!\n");

	//мультиплексирование
	printf("Мультиплексирование (select):\n");
	fd_set set_for_read, set_for_write;    //ровно по 1024 бит 
	printf("Цикл:\n");
	//узнаем наибольший номер дескриптора, чтоб узнать сколько битов в наборе нужно отслеживать
	int max=fd_in<fd_out ? fd_out : fd_in;
	//буфер на сервере (на случай задержки отправки)
	struct Buf *root=NULL, *tail=NULL;
	int is_out=0;
	//запускаем цикл проверки
	long long cnt=0;
	while(1){
		//инициализация
		FD_ZERO(&set_for_read); 
		FD_ZERO(&set_for_write);
		
		//добавляем в набор отслеживаемый на чтение дескриптор
		printf("\tдобавляем in...");
		FD_SET(fd_in,&set_for_read);
		printf("ok!\n");
		if(is_out){
			printf("\tдобавляем out...");
			FD_SET(fd_out,&set_for_write);
			printf("ok!\n");
		}
	        fflush(stdout);

		//запускаем проверку готовности
		++cnt;
		printf("\n%lld)-->select...",cnt);fflush(stdout);
		select(max+1,&set_for_read,&set_for_write,NULL,NULL);//эта команда сбрасывает не готовые биты поля, поэтому нужно регистрировать поновой	
		printf("ok!\n");
		//проснулись
		if(FD_ISSET(fd_out,&set_for_write)){ //проверка готовности писать
			printf("-->write...");
			if(root==NULL)
				FD_CLR(fd_out,&set_for_write);//снимаем с регистрации, т.к. нечего писать
			else{
				int len=write(fd_out,root->data,root->len);
				if(len!=-1){//успешно записано
					printf("ok!\n");
					struct Buf * tmp=root->next;
					free(root);
					root=tmp;
					if(root==NULL){ //все записано
						tail=NULL;
						is_out=0;
					}
				}
			}
		}
		if(FD_ISSET(fd_in,&set_for_read)){ //проверка готовности чтения
			printf("-->read...");
			//читаем из канала
			char data[LEN+1];
			int len=read(fd_in,data,LEN);
			if(-1!=len){
				if(root==NULL)
					tail=root=(struct Buf*)malloc(sizeof(struct Buf));
				else{
					tail->next=(struct Buf*)malloc(sizeof(struct Buf));
					tail=tail->next;
				}
				tail->next=NULL;
				tail->len=len;
				memcpy(tail->data,data,len);
				data[len]='\0';
//.........这里部分代码省略.........
开发者ID:eturin,项目名称:linux,代码行数:101,代码来源:server.c


示例16: main

该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ FD_ISSET函数代码示例发布时间:2022-05-30
下一篇:
C++ FDT_CHECK_HEADER函数代码示例发布时间:2022-05-30
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap