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

C++ FD_ISSET函数代码示例

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

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



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

示例1: ldap_pvt_connect


//.........这里部分代码省略.........
				msg.msg_iov = &iov;
				msg.msg_iovlen = 1;
# ifdef HAVE_STRUCT_MSGHDR_MSG_CONTROL
				msg.msg_control = control_un.control;
				msg.msg_controllen = sizeof( control_un.control );
				msg.msg_flags = 0;

				cmsg = CMSG_FIRSTHDR( &msg );
				cmsg->cmsg_len = CMSG_LEN( sizeof(int) );
				cmsg->cmsg_level = SOL_SOCKET;
				cmsg->cmsg_type = SCM_RIGHTS;

				*((int *)CMSG_DATA(cmsg)) = fds[0];
# else
				msg.msg_accrights = (char *)fds;
				msg.msg_accrightslen = sizeof(int);
# endif /* HAVE_STRUCT_MSGHDR_MSG_CONTROL */
				getpeername( s, sa, &salen );
				fchmod( fds[0], S_ISUID|S_IRWXU );
				write( fds[1], sa, salen );
				sendmsg( s, &msg, 0 );
				close(fds[0]);
				close(fds[1]);
			}
		}
#endif
		return 0;
	}

	if ( errno != EINPROGRESS && errno != EWOULDBLOCK ) return -1;
	
#ifdef notyet
	if ( async ) return -2;
#endif

#ifdef HAVE_POLL
	{
		struct pollfd fd;
		int timeout = INFTIM;

		if( opt_tv != NULL ) timeout = TV2MILLISEC( &tv );

		fd.fd = s;
		fd.events = POLL_WRITE;

		do {
			fd.revents = 0;
			rc = poll( &fd, 1, timeout );
		} while( rc == AC_SOCKET_ERROR && errno == EINTR &&
			LDAP_BOOL_GET(&ld->ld_options, LDAP_BOOL_RESTART ));

		if( rc == AC_SOCKET_ERROR ) return rc;

		if( fd.revents & POLL_WRITE ) {
			if ( ldap_pvt_is_socket_ready(ld, s) == -1 ) return -1;
			if ( ldap_pvt_ndelay_off(ld, s) == -1 ) return -1;
#ifdef LDAP_PF_LOCAL_SENDMSG
			goto sendcred;
#else
			return ( 0 );
#endif
		}
	}
#else
	{
		fd_set wfds, *z=NULL;

#ifdef FD_SETSIZE
		if ( s >= FD_SETSIZE ) {
			rc = AC_SOCKET_ERROR;
			tcp_close( s );
			ldap_pvt_set_errno( EMFILE );
			return rc;
		}
#endif
		do { 
			FD_ZERO(&wfds);
			FD_SET(s, &wfds );
			rc = select( ldap_int_tblsize, z, &wfds, z, opt_tv ? &tv : NULL );
		} while( rc == AC_SOCKET_ERROR && errno == EINTR &&
			LDAP_BOOL_GET(&ld->ld_options, LDAP_BOOL_RESTART ));

		if( rc == AC_SOCKET_ERROR ) return rc;

		if ( FD_ISSET(s, &wfds) ) {
			if ( ldap_pvt_is_socket_ready(ld, s) == -1 ) return -1;
			if ( ldap_pvt_ndelay_off(ld, s) == -1 ) return -1;
#ifdef LDAP_PF_LOCAL_SENDMSG
			goto sendcred;
#else
			return ( 0 );
#endif
		}
	}
#endif

	oslocal_debug(ld, "ldap_connect_timeout: timed out\n",0,0,0);
	ldap_pvt_set_errno( ETIMEDOUT );
	return ( -1 );
}
开发者ID:FarazShaikh,项目名称:LikewiseSMB2,代码行数:101,代码来源:os-local.c


示例2: main


//.........这里部分代码省略.........
		}
#endif
#ifdef USE_MINIUPNPDCTL
		if(sctl >= 0) {
			FD_SET(sctl, &readset);
			max_fd = MAX( max_fd, sctl);
		}

		for(ectl = ctllisthead.lh_first; ectl; ectl = ectl->entries.le_next)
		{
			if(ectl->socket >= 0) {
				FD_SET(ectl->socket, &readset);
				max_fd = MAX( max_fd, ectl->socket);
			}
		}
#endif

#ifdef ENABLE_EVENTS
		upnpevents_selectfds(&readset, &writeset, &max_fd);
#endif

		if(select(max_fd+1, &readset, &writeset, 0, &timeout) < 0)
		{
			if(quitting) goto shutdown;
			if(errno == EINTR) continue; /* interrupted by a signal, start again */
			syslog(LOG_ERR, "select(all): %m");
			syslog(LOG_ERR, "Failed to select open sockets. EXITING");
			return 1;	/* very serious cause of error */
		}
#ifdef USE_MINIUPNPDCTL
		for(ectl = ctllisthead.lh_first; ectl;)
		{
			ectlnext =  ectl->entries.le_next;
			if((ectl->socket >= 0) && FD_ISSET(ectl->socket, &readset))
			{
				char buf[256];
				int l;
				l = read(ectl->socket, buf, sizeof(buf));
				if(l > 0)
				{
					/*write(ectl->socket, buf, l);*/
					write_command_line(ectl->socket, argc, argv);
					write_option_list(ectl->socket);
					write_permlist(ectl->socket, upnppermlist, num_upnpperm);
					write_upnphttp_details(ectl->socket, upnphttphead.lh_first);
					write_ctlsockets_list(ectl->socket, ctllisthead.lh_first);
					write_ruleset_details(ectl->socket);
#ifdef ENABLE_EVENTS
					write_events_details(ectl->socket);
#endif
					/* close the socket */
					close(ectl->socket);
					ectl->socket = -1;
				}
				else
				{
					close(ectl->socket);
					ectl->socket = -1;
				}
			}
			if(ectl->socket < 0)
			{
				LIST_REMOVE(ectl, entries);
				free(ectl);
			}
			ectl = ectlnext;
开发者ID:chinshou,项目名称:miniupnp,代码行数:67,代码来源:miniupnpd.c


示例3: main

int main(int argc, char* argv[])
{
  int sockfd, fdmax, i, port;
  char *host;
  struct hostent *hp;
  struct sockaddr_in server_addr;
  fd_set master;
  fd_set read_fds;
  
  if (argc==4) {
    host = argv[1];
    port = atoi(argv[2]);
    if(strlen(argv[3]) > NAME_SIZE){
      fprintf(stderr, "User name too long");
      exit(1);
    }
    else{
      strcpy(username, argv[3]);
      printf("%s\n", username);
    }
  }
  else {
    fprintf(stderr, "usage: ./client <host> <port> <username>\n");
    exit(1);
  }

  /* translate host name into peer’s IP address */
  hp = gethostbyname(host);

  if (!hp) {
    fprintf(stderr, "unknown host: %s\n", host);
    exit(1);
  }

  if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
    perror("Socket");
    exit(1);
  }
  server_addr.sin_family = AF_INET;
  server_addr.sin_port = htons(port);
  server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
  memset(server_addr.sin_zero, '\0', sizeof server_addr.sin_zero);
	
  if(connect(sockfd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1) {
    perror("connect");
    exit(1);
  }

  printf("%s\n", username);
  if(send(sockfd, username,sizeof(username), 0) < 0){
    perror("name send");
    exit(1);
  }
  
  FD_ZERO(&master);
  FD_ZERO(&read_fds);
  FD_SET(0, &master);
  FD_SET(sockfd, &master);
  fdmax = sockfd;

  init_interface();
  
  while(1){
    read_fds = master;
    if(select(fdmax+1, &read_fds, NULL, NULL, NULL) == -1){
      perror("select");
      exit(4);
    }
		
    for(i=0; i <= fdmax; i++ )
      if(FD_ISSET(i, &read_fds))
	send_recv(i, sockfd);
  }
  out_printf("client-quited\n");
  close(sockfd);
  return 0;
}
开发者ID:leoomi,项目名称:projeto_mc833,代码行数:77,代码来源:client.c


示例4: iopause

void iopause(iopause_fd *x,unsigned int len,struct taia *deadline,struct taia *stamp)
{
  struct taia t;
  int millisecs;
  double d;
  int i;

  if (taia_less(deadline,stamp))
    millisecs = 0;
  else {
    t = *stamp;
    taia_sub(&t,deadline,&t);
    d = taia_approx(&t);
    if (d > 1000.0) d = 1000.0;
    millisecs = d * 1000.0 + 20.0;
  }

  for (i = 0;i < len;++i)
    x[i].revents = 0;

#ifdef IOPAUSE_POLL

  poll(x,len,millisecs);
  /* XXX: some kernels apparently need x[0] even if len is 0 */
  /* XXX: how to handle EAGAIN? are kernels really this dumb? */
  /* XXX: how to handle EINVAL? when exactly can this happen? */

#else
{

  struct timeval tv;
  fd_set rfds;
  fd_set wfds;
  int nfds;
  int fd;

  FD_ZERO(&rfds);
  FD_ZERO(&wfds);

  nfds = 1;
  for (i = 0;i < len;++i) {
    fd = x[i].fd;
    if (fd < 0) continue;
    if (fd >= 8 * sizeof(fd_set)) continue; /*XXX*/

    if (fd >= nfds) nfds = fd + 1;
    if (x[i].events & IOPAUSE_READ) FD_SET(fd,&rfds);
    if (x[i].events & IOPAUSE_WRITE) FD_SET(fd,&wfds);
  }

  tv.tv_sec = millisecs / 1000;
  tv.tv_usec = 1000 * (millisecs % 1000);

  if (select(nfds,&rfds,&wfds,(fd_set *) 0,&tv) <= 0)
    return;
    /* XXX: for EBADF, could seek out and destroy the bad descriptor */

  for (i = 0;i < len;++i) {
    fd = x[i].fd;
    if (fd < 0) continue;
    if (fd >= 8 * sizeof(fd_set)) continue; /*XXX*/

    if (x[i].events & IOPAUSE_READ)
      if (FD_ISSET(fd,&rfds)) x[i].revents |= IOPAUSE_READ;
    if (x[i].events & IOPAUSE_WRITE)
      if (FD_ISSET(fd,&wfds)) x[i].revents |= IOPAUSE_WRITE;
  }

}
#endif

}
开发者ID:alexkoltun,项目名称:logmind,代码行数:72,代码来源:iopause.c


示例5: server_mode

int server_mode(const struct hostent *host, const unsigned int port) {

	/* Local variables */
	socklen_t addr_length; /* Sockaddr length */
	struct sockaddr_in sa; /* Socket remote target info structure */
	fd_set rfds; /* File descriptor set for select() */
	int i, sockfd, conn_sockfd, maxfd, err; /* listening socket fd, client socket fd, max fd number */

	/* Debug message */
	printf("[DEBUG] Listen on %s : %d\n", host->h_name, port);

	/* Compute socket bind structure */
	sa.sin_family = AF_INET;
	sa.sin_port = htons(port);
	memcpy(&sa.sin_addr, host->h_addr_list[0], sizeof(sa.sin_addr));

	/* Debug message */
	puts("[DEBUG] Opening socket ...");

	/* Open socket */
	if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {

		/* Drop error message */
		perror("socket()");

		/* Return with error */
		return SOCKET_ERROR;
	}

	/* Debug message */
	puts("[DEBUG] Binding socket ...");

	/* Bind socket to local address */
	if (bind(sockfd, (struct sockaddr*) &sa, sizeof sa) == -1) {

		/* Drop error message */
		perror("bind()");

		/* Return with error */
		return SOCKET_ERROR;
	}

	/* Debug message */
	puts("[DEBUG] Start listening ...");

	/* Start listening on socket */
	if (listen(sockfd, 5) == -1) {

		/* Drop error message */
		perror("listen()");

		/* Return with error */
		return SOCKET_ERROR;
	}

	/* CTRL+C FTW #meGusta */
	for (;;) {

		/* Initialize fd_set and maxfd */
		FD_ZERO(&rfds);
		FD_SET(sockfd, &rfds);
		maxfd = sockfd;

		/* Add all available clients into fd_set */
		for (i = 0; i < NB_MAX_CLIENTS; ++i) {

			/* If client is available */
			if (!clients[i].free) {

				/* Add it to fd_set */
				FD_SET(clients[i].sockfd, &rfds);

				/* Update maxfd */
				if (clients[i].sockfd > maxfd)
					maxfd = clients[i].sockfd;
			}
		}

		/* Debug message */
		/*puts("[DEBUG] Clients list reloaded !");*/

		switch (select(maxfd + 1, &rfds, NULL, NULL, NULL )) {
		case -1: /* If error */
			/* Drop error message */
			perror("select()");

			/* Return with error */
			return SELECT_ERROR;
			break;

		default: /* Socket event */

			/* If event on listening socket */
			if (FD_ISSET(sockfd, &rfds)) {

				/* Accept new incoming socket */
				if ((conn_sockfd = accept(sockfd, (struct sockaddr*) &sa,
						&addr_length)) == -1) {

					/* Drop error message */
//.........这里部分代码省略.........
开发者ID:khalebios,项目名称:mini_files_transfert,代码行数:101,代码来源:server.c


示例6: main


//.........这里部分代码省略.........
        diagnostic_.update();
      }
      
      ROS_INFO("Opened joystick: %s. deadzone_: %f.", joy_dev_.c_str(), deadzone_);
      open_ = true;
      diagnostic_.force_update();
      
      bool tv_set = false;
      bool publication_pending = false;
      tv.tv_sec = 1;
      tv.tv_usec = 0;
      sensor_msgs::Joy joy_msg; // Here because we want to reset it on device close.
      while (nh_.ok()) 
      {
        ros::spinOnce();
        
        bool publish_now = false;
        bool publish_soon = false;
        FD_ZERO(&set);
        FD_SET(joy_fd, &set);
        
        //ROS_INFO("Select...");
        int select_out = select(joy_fd+1, &set, NULL, NULL, &tv);
        //ROS_INFO("Tick...");
        if (select_out == -1)
        {
          tv.tv_sec = 0;
          tv.tv_usec = 0;
          //ROS_INFO("Select returned negative. %i", ros::isShuttingDown());
          continue;
          //				break; // Joystick is probably closed. Not sure if this case is useful.
        }
        
        if (FD_ISSET(joy_fd, &set))
        {
          if (read(joy_fd, &event, sizeof(js_event)) == -1 && errno != EAGAIN)
            break; // Joystick is probably closed. Definitely occurs.
          
          //ROS_INFO("Read data...");
          joy_msg.header.stamp = ros::Time().now();
          event_count_++;
          switch(event.type)
          {
          case JS_EVENT_BUTTON:
          case JS_EVENT_BUTTON | JS_EVENT_INIT:
            if(event.number >= joy_msg.buttons.size())
            {
              int old_size = joy_msg.buttons.size();
              joy_msg.buttons.resize(event.number+1);
              for(unsigned int i=old_size;i<joy_msg.buttons.size();i++)
                joy_msg.buttons[i] = 0.0;
            }
            joy_msg.buttons[event.number] = (event.value ? 1 : 0);
            // For initial events, wait a bit before sending to try to catch
            // all the initial events.
            if (!(event.type & JS_EVENT_INIT))
            {
              publish_now = true;
              last_event_time = ros::Time::now();
            }
            else
              publish_soon = true;
            break;
          case JS_EVENT_AXIS:
          case JS_EVENT_AXIS | JS_EVENT_INIT:
            if(event.number >= joy_msg.axes.size())
开发者ID:pxlong,项目名称:segwayrmp,代码行数:67,代码来源:joy_node.cpp


示例7: fcntl

// GLIB loop intergration workaround
int Main::EcoreSelectInterceptor(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout)
{
#if 0
    // Check each descriptor to see if it is valid
    for (int i = 0; i < nfds; i++)
    {
        if (FD_ISSET(i, readfds) || FD_ISSET(i, writefds) || FD_ISSET(i, exceptfds))
        {
            // Try to get descriptor flags
            int result = fcntl(i, F_GETFL);

            if (result == -1)
            {
                if (errno == EBADF)
                {
                    // This a bad descriptor. Remove all occurrences of it.
                    if (FD_ISSET(i, readfds))
                    {
                        LogPedantic("GLIB_LOOP_INTEGRATION_WORKAROUND: Bad read descriptor: " << i);
                        FD_CLR(i, readfds);
                    }

                    if (FD_ISSET(i, writefds))
                    {
                        LogPedantic("GLIB_LOOP_INTEGRATION_WORKAROUND: Bad write descriptor: " << i);
                        FD_CLR(i, writefds);
                    }

                    if (FD_ISSET(i, exceptfds))
                    {
                        LogPedantic("GLIB_LOOP_INTEGRATION_WORKAROUND: Bad exception descriptor: " << i);
                        FD_CLR(i, exceptfds);
                    }
                }
                else
                {
                    // Unexpected error
                    Assert(0);
                }
            }
        }
    }

    // Find out new maximum
    int newNfds = 0;

    for (int i = 0; i < nfds; i++)
    {
        if (FD_ISSET(i, readfds) || FD_ISSET(i, writefds) || FD_ISSET(i, exceptfds))
            newNfds = i;
    }

    return MainSingleton::Instance().m_oldEcoreSelect(newNfds + 1, readfds, writefds, exceptfds, timeout);

#else

    // We have to check error code here and make another try because of some glib error's.
    fd_set rfds, wfds, efds;
    memcpy(&rfds, readfds, sizeof(fd_set));
    memcpy(&wfds, writefds, sizeof(fd_set));
    memcpy(&efds, exceptfds, sizeof(fd_set));

    int ret = MainSingleton::Instance().m_oldEcoreSelect(nfds, readfds, writefds, exceptfds, timeout);

    if (ret == -1)
    {
        // Check each descriptor to see if it is valid
        for (int i = 0; i < nfds; i++)
        {
            if (FD_ISSET(i, readfds) || FD_ISSET(i, writefds) || FD_ISSET(i, exceptfds))
            {
                // Try to get descriptor flags
                int result = fcntl(i, F_GETFL);

                if (result == -1)
                {
                    if (errno == EBADF)
                    {
                        // This a bad descriptor. Remove all occurrences of it.
                        if (FD_ISSET(i, readfds))
                        {
                            LogPedantic("GLIB_LOOP_INTEGRATION_WORKAROUND: Bad read descriptor: " << i);
                            FD_CLR(i, readfds);
                        }

                        if (FD_ISSET(i, writefds))
                        {
                            LogPedantic("GLIB_LOOP_INTEGRATION_WORKAROUND: Bad write descriptor: " << i);
                            FD_CLR(i, writefds);
                        }

                        if (FD_ISSET(i, exceptfds))
                        {
                            LogPedantic("GLIB_LOOP_INTEGRATION_WORKAROUND: Bad exception descriptor: " << i);
                            FD_CLR(i, exceptfds);
                        }
                    }
                    else
                    {
//.........这里部分代码省略.........
开发者ID:tizenorg,项目名称:platform.framework.web.wrt-commons,代码行数:101,代码来源:main.cpp


示例8: main

int main(int argc, char **argv)
{
	int fd = socket(AF_INET, SOCK_STREAM, 0); // TCP

	int on = 1;
	setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof on);

	struct sockaddr_in srvaddr;
	bzero(&srvaddr, sizeof srvaddr);
	srvaddr.sin_family = AF_INET;
	srvaddr.sin_addr.s_addr = inet_addr(HOST);
	srvaddr.sin_port = htons(DEFAULT_PORT);

	if(connect(fd, (struct sockaddr *)&srvaddr, sizeof srvaddr) == -1)
	{
		perror("connect() error");
		exit(1);
	}

	struct sockaddr_in myaddr;
	socklen_t len = sizeof myaddr;
	bzero(&myaddr, len);
	getsockname(fd, (struct sockaddr *)&myaddr, &len);
	printf("my port: %hu\n", htons(myaddr.sin_port));


	//pthread_t tid;
	//pthread_create(&tid, NULL, routine, (void *)fd);


	char buf[100];
	
	fd_set rset, wset, eset; // 这些是描述符集合
	struct timeval a;
	a.tv_sec = 0;
	a.tv_usec = 0;
	
	while(1)
	{
#if 0 
		FD_ZERO(&rset); // 添加在这里面的描述符,我们关注他们的“读就绪”状态
		FD_ZERO(&wset); // 添加在这里面的描述符,我们关注他们的“写就绪”状态
		FD_ZERO(&eset); // 添加在这里面的描述符,我们关注他们的“异常就绪”状态
		FD_SET(fd, &rset);
		FD_SET(STDIN_FILENO, &rset); // 将两个描述符添加到rset里面!

		select(fd+1, &rset, &wset, &eset, &a);
		
		bzero(&buf, 100);
		if(FD_ISSET(STDIN_FILENO, &rset)) // 用户输入数据了!
		{
			fgets(buf, 100, stdin);				
			write(fd, buf, strlen(buf));
		}
#endif
		FD_ZERO(&rset); // 添加在这里面的描述符,我们关注他们的“读就绪”状态
		FD_ZERO(&wset); // 添加在这里面的描述符,我们关注他们的“写就绪”状态
		FD_ZERO(&eset); // 添加在这里面的描述符,我们关注他们的“异常就绪”状态
		FD_SET(fd, &rset);
		FD_SET(STDIN_FILENO, &rset); // 将两个描述符添加到rset里面!

		select(fd+1, &rset, &wset, &eset, &a);
		
		char buf[100];
		bzero(buf, 100);
		if(FD_ISSET(fd, &rset)) // 对方有消息来了!
		{
			if(read(fd, buf, 100) == 0)
				break;
			printf("broadcast: %s\n", buf);
		}
		if(FD_ISSET(STDIN_FILENO, &rset)) // 用户输入数据了!
		{
			fgets(buf, 100, stdin);
			write(fd, buf, strlen(buf));
		}
	}

	return 0;
}
开发者ID:lanselambor,项目名称:HomeServer,代码行数:80,代码来源:client.c


示例9: netsettime

/*
 * Set the date in the machines controlled by timedaemons by communicating the
 * new date to the local timedaemon.  If the timedaemon is in the master state,
 * it performs the correction on all slaves.  If it is in the slave state, it
 * notifies the master that a correction is needed.
 * Returns 0 on success.  Returns > 0 on failure, setting retval to 2;
 */
int
netsettime(time_t tval)
{
	struct timeval tout;
	struct servent *sp;
	struct tsp msg;
	struct sockaddr_in lsin, dest, from;
	fd_set ready;
	long waittime;
	int s, port, timed_ack, found, lerr;
	socklen_t length;
	char hostname[MAXHOSTNAMELEN];

	if ((sp = getservbyname("timed", "udp")) == NULL) {
		warnx("timed/udp: unknown service");
		return (retval = 2);
	}

	dest.sin_port = sp->s_port;
	dest.sin_family = AF_INET;
	dest.sin_addr.s_addr = htonl((u_long)INADDR_ANY);
	s = socket(AF_INET, SOCK_DGRAM, 0);
	if (s < 0) {
		if (errno != EPROTONOSUPPORT)
			warn("timed");
		return (retval = 2);
	}

	memset(&lsin, 0, sizeof(lsin));
	lsin.sin_family = AF_INET;
	for (port = IPPORT_RESERVED - 1; port > IPPORT_RESERVED / 2; port--) {
		lsin.sin_port = htons((u_short)port);
		if (bind(s, (struct sockaddr *)&lsin, sizeof(lsin)) >= 0)
			break;
		if (errno == EADDRINUSE)
			continue;
		if (errno != EADDRNOTAVAIL)
			warn("bind");
		goto bad;
	}
	if (port == IPPORT_RESERVED / 2) {
		warnx("all ports in use");
		goto bad;
	}
	memset(&msg, 0, sizeof(msg));
	msg.tsp_type = TSP_SETDATE;
	msg.tsp_vers = TSPVERSION;
	if (gethostname(hostname, sizeof(hostname))) {
		warn("gethostname");
		goto bad;
	}
	(void)strlcpy(msg.tsp_name, hostname, sizeof(msg.tsp_name));
	msg.tsp_seq = htons((u_short)0);
	msg.tsp_time.tv_sec = htonl((u_long)tval);
	msg.tsp_time.tv_usec = htonl((u_long)0);
	length = sizeof(struct sockaddr_in);
	if (connect(s, (struct sockaddr *)&dest, length) < 0) {
		warn("connect");
		goto bad;
	}
	if (send(s, (char *)&msg, sizeof(struct tsp), 0) < 0) {
		if (errno != ECONNREFUSED)
			warn("send");
		goto bad;
	}

	timed_ack = -1;
	waittime = WAITACK;
loop:
	tout.tv_sec = waittime;
	tout.tv_usec = 0;

	FD_ZERO(&ready);
	FD_SET(s, &ready);
	found = select(FD_SETSIZE, &ready, (fd_set *)0, (fd_set *)0, &tout);

	length = sizeof(lerr);
	if (!getsockopt(s,
	    SOL_SOCKET, SO_ERROR, (char *)&lerr, &length) && lerr) {
		if (lerr != ECONNREFUSED)
			warnc(lerr, "send (delayed error)");
		goto bad;
	}

	if (found > 0 && FD_ISSET(s, &ready)) {
		length = sizeof(struct sockaddr_in);
		if (recvfrom(s, &msg, sizeof(struct tsp), 0,
		    (struct sockaddr *)&from, &length) < 0) {
			if (errno != ECONNREFUSED)
				warn("recvfrom");
			goto bad;
		}
		msg.tsp_seq = ntohs(msg.tsp_seq);
//.........这里部分代码省略.........
开发者ID:ajburton,项目名称:freebsd,代码行数:101,代码来源:netdate.c


示例10: FD_ZERO

    void HttpServer::WaitMessage(uint32_t ms)
    {
      fd_set fdsr;
      struct timeval tv;
      int max_sock = m_sock;

      tv.tv_sec = ms / 1000;
      tv.tv_usec = (ms % 1000 ) / 1000;

      FD_ZERO(&fdsr);

#ifdef _WIN32
      /* on Windows, a socket is not an int but a SOCKET (unsigned int) */
      FD_SET((SOCKET)m_sock, &fdsr);
#else
      FD_SET(m_sock, &fdsr);
#endif

      for(std::list<int>::iterator it = m_clients.begin() ; it != m_clients.end() ; ++it)
      {
#ifdef _WIN32
        FD_SET((SOCKET)(*it), &fdsr);
#else
        FD_SET((*it), &fdsr);
#endif

        if((*it) > max_sock)
        {
          max_sock = (*it);
        }
      }

      max_sock++;

      if(select(max_sock, &fdsr, NULL, NULL, ms ? &tv : NULL) > 0)
      {
        if(FD_ISSET(m_sock, &fdsr))
        {
          Accept();
        }

        for(std::list<int>::iterator it = m_clients.begin() ; it != m_clients.end() ; ++it)
        {
          if(FD_ISSET((*it), &fdsr))
          {
            Recv((*it));
          }
        }

        /* remove disconnect socket descriptor */
        for(std::list<int>::iterator it = m_purge.begin() ; it != m_purge.end() ; ++it)
        {
          m_clients.remove((*it));
          m_httpmsgs.erase((*it));
        }

        /* purge disconnected list */
        m_purge.erase(m_purge.begin(), m_purge.end());
      }
      else
      {
        /* error */
      }
    }
开发者ID:un44444444,项目名称:jsonrpc-cpp-mod-http,代码行数:64,代码来源:jsonrpc_httpserver.cpp


示例11: read


//.........这里部分代码省略.........
					//   cursor doesn't reflect actual length of the string that's sent back
					tty_con.cursor = strlen( tty_con.buffer );
					if ( tty_con.cursor > 0 ) {
						if ( tty_con.buffer[0] == '\\' ) {
							for ( i = 0; i <= tty_con.cursor; i++ )
							{
								tty_con.buffer[i] = tty_con.buffer[i + 1];
							}
							tty_con.cursor--;
						}
					}
					tty_Show();
					return NULL;
				}
				avail = read( 0, &key, 1 );
				if ( avail != -1 ) {
					// VT 100 keys
					if ( key == '[' || key == 'O' ) {
						avail = read( 0, &key, 1 );
						if ( avail != -1 ) {
							switch ( key )
							{
							case 'A':
								history = Hist_Prev();
								if ( history ) {
									tty_Hide();
									tty_con = *history;
									tty_Show();
								}
								tty_FlushIn();
								return NULL;
								break;
							case 'B':
								history = Hist_Next();
								tty_Hide();
								if ( history ) {
									tty_con = *history;
								} else
								{
									Field_Clear( &tty_con );
								}
								tty_Show();
								tty_FlushIn();
								return NULL;
								break;
							case 'C':
								return NULL;
							case 'D':
								return NULL;
							}
						}
					}
				}
				Com_DPrintf( "droping ISCTL sequence: %d, tty_erase: %d\n", key, tty_erase );
				tty_FlushIn();
				return NULL;
			}
			// push regular character
			tty_con.buffer[tty_con.cursor] = key;
			tty_con.cursor++;
			// print the current line (this is differential)
			write( 1, &key, 1 );
		}
		return NULL;
	} else
	{
		int len;
		fd_set fdset;
		struct timeval timeout;

		if ( !com_dedicated || !com_dedicated->value ) {
			return NULL;
		}

		if ( !stdin_active ) {
			return NULL;
		}

		FD_ZERO( &fdset );
		FD_SET( 0, &fdset ); // stdin
		timeout.tv_sec = 0;
		timeout.tv_usec = 0;
		if ( select( 1, &fdset, NULL, NULL, &timeout ) == -1 || !FD_ISSET( 0, &fdset ) ) {
			return NULL;
		}

		len = read( 0, text, sizeof( text ) );
		if ( len == 0 ) { // eof!
			stdin_active = qfalse;
			return NULL;
		}

		if ( len < 1 ) {
			return NULL;
		}
		text[len - 1] = 0; // rip off the /n and terminate

		return text;
	}
}
开发者ID:chegestar,项目名称:omni-bot,代码行数:101,代码来源:unix_main.c


示例12: gwrl_bkd_gather

void gwrl_bkd_gather(gwrl * rl) {
	int res = 0;
	gwrlevt_flags_t newflags = 0;
	fd_set fds[3];
	gwrlsrc * src = NULL;
	gwrlsrc_file * fsrc = NULL;
	gwrlevt * evt = NULL;
	gwrlbkd * bkd = rl->backend;
	gwrlbkd_select * sbkd = _gwrlbkds(bkd);
	
	//setup timeout for select
	struct timeval timeout;
	struct timeval * timeoutp = &timeout;
	if(bkd->timeout.tv_sec == sec_min && bkd->timeout.tv_nsec == nsec_min) {
		timeoutp = NULL;
	} else {
		gwtm_timespec_to_timeval(&bkd->timeout,&timeout);
	}
	
	//if sleep isn't allowed set timeout to 0
	if(!timeoutp && flisset(rl->flags,GWRL_NOSLEEP)) {
		timeoutp = &timeout;
		timeout.tv_sec = 0;
		timeout.tv_usec = 0;

		#ifdef GWRL_COVERAGE_INTERNAL_ASSERT_VARS
			if(asserts_var1 == gwrlbkd_no_sleep_assert_true) {
				asserts_var2 = true;
			}
		#endif
	}
	
	//initialize fds
	FD_ZERO(&(fds[0]));
	FD_ZERO(&(fds[1]));
	FD_ZERO(&(fds[2]));
	
	//reset fds
	memcpy(&(fds[0]),&(sbkd->src[0]),sizeof(fd_set));
	memcpy(&(fds[1]),&(sbkd->src[1]),sizeof(fd_set));
	memcpy(&(fds[2]),&(sbkd->src[2]),sizeof(fd_set));
	
	//call select, wrapped in sleeping flags so other threads can wake us
	flset(rl->flags,GWRL_SLEEPING);
	res = select(sbkd->maxfd+1,&(fds[0]),&(fds[1]),&(fds[2]),timeoutp);
	flclr(rl->flags,GWRL_SLEEPING);
	
	if(res == 0) return; //timeout
	
	//break and let the event loop continue or start over.
	//if a signal did happen, the event loop may have an
	//event that needs processing.
	if(res < 0 && (errno == EINTR || errno == EAGAIN)) return;
	
	//bad fd, unforunately select doesn't tell us which
	//one it was so we have to search for it.
	if(res < 0 && errno == EBADF) {
		gwrl_src_file_find_badfd_post_evt(rl);
		return;
	}
	
	//invalid timeout or invalid number of fds.
	if(res < 0 && errno == EINVAL) {
		//invalid timeout, break and let process events recalculate timeouts.
		if(timeout.tv_sec < 0 || timeout.tv_usec < 0) return;
		
		//nfds parameter to select() is too large, not sure how to handle
		fprintf(stderr,"select: file descriptor limit reached. exiting. \n");
		exit(1);
	}
	
	//valid events are ready
	if(res > 0) {
		fsrc = _gwrlsrcf(rl->sources[GWRL_SRC_TYPE_FILE]);
		while(fsrc) {
			src = _gwrlsrc(fsrc);
			newflags = 0;
			
			if(!flisset(src->flags,GWRL_ENABLED)) {
				fsrc = _gwrlsrcf(src->next);
				continue;
			}
			
			if(FD_ISSET(fsrc->fd,&fds[0])) flset(newflags,GWRL_RD);
			if(FD_ISSET(fsrc->fd,&fds[1])) flset(newflags,GWRL_WR);
			if(FD_ISSET(fsrc->fd,&fds[2])) flset(newflags,GWRL_RD);
			
			if(newflags > 0) {
				evt = gwrl_evt_createp(rl,src,src->callback,src->userdata,fsrc->fd,newflags);
				gwrl_post_evt(rl,evt);
			}
			
			fsrc = _gwrlsrcf(src->next);
		}
	}
}
开发者ID:ChinaXing,项目名称:libgwrl,代码行数:96,代码来源:event_select.c


示例13: wi_socket_wait_multiple

wi_socket_t * wi_socket_wait_multiple(wi_array_t *array, wi_time_interval_t timeout) {
	wi_enumerator_t		*enumerator;
	wi_socket_t			*socket, *waiting_socket = NULL;
	struct timeval		tv;
	fd_set				rfds, wfds;
	int					state, max_sd;

	tv = wi_dtotv(timeout);
	max_sd = -1;

	FD_ZERO(&rfds);
	FD_ZERO(&wfds);

	wi_array_rdlock(array);
	
	enumerator = wi_array_data_enumerator(array);
	
	while((socket = wi_enumerator_next_data(enumerator))) {
		if(wi_string_length(socket->buffer) > 0) {
			waiting_socket = socket;
			
			break;
		}
		
		if(socket->direction & WI_SOCKET_READ)
			FD_SET(socket->sd, &rfds);

		if(socket->direction & WI_SOCKET_WRITE)
			FD_SET(socket->sd, &wfds);

		if(socket->sd > max_sd)
			max_sd = socket->sd;
	}

	wi_array_unlock(array);
	
	if(waiting_socket)
		return waiting_socket;
	
	state = select(max_sd + 1, &rfds, &wfds, NULL, (timeout > 0.0) ? &tv : NULL);
	
	if(state < 0) {
		wi_error_set_errno(errno);

		return NULL;
	}
	
	wi_array_rdlock(array);

	enumerator = wi_array_data_enumerator(array);
	
	while((socket = wi_enumerator_next_data(enumerator))) {
		if(FD_ISSET(socket->sd, &rfds) || FD_ISSET(socket->sd, &wfds)) {
			waiting_socket = socket;

			break;
		}
	}
	
	wi_array_unlock(array);
	
	return waiting_socket;
}
开发者ID:asvitkine,项目名称:phxd,代码行数:63,代码来源:wi-socket.c


示例14: ident_check

void ident_check(struct descriptor_data *d, int pulse)
{
  fd_set fd, efd;
  int rc, rmt_port, our_port, len;
  char user[256], *p;

  extern struct timeval null_time;
  extern int port;

  /*
   * Each pulse, this checks if the ident is ready to proceed to the
   * next state, by calling select to see if the socket is writeable
   * (connected) or readable (response waiting).  
   */

  switch (STATE(d)) {
    case CON_IDCONING:
      /* waiting for connect() to finish */

      if (d->ident_sock != INVALID_SOCKET) {
        FD_ZERO(&fd);
        FD_ZERO(&efd);
        FD_SET(d->ident_sock, &fd);
        FD_SET(d->ident_sock, &efd);
      }

      if ((rc = select(d->ident_sock + 1, (fd_set *) 0, &fd, &efd, &null_time)) == 0)
        break;

      else if (rc < 0) {
        logerror("ident check select (conning)");
        STATE(d) = CON_ASKNAME;
        break;
      }

      if (FD_ISSET(d->ident_sock, &efd)) {
        /* exception, such as failure to connect */
        STATE(d) = CON_ASKNAME;
        break;
      }

      STATE(d) = CON_IDCONED;
      break;

    case CON_IDCONED:
      /* connected, write request */

      sprintf(buf, "%d, %d\n\r", ntohs(d->peer_port), port);

      len = strlen(buf);
#ifdef CIRCLE_WINDOWS
      if (send(d->ident_sock, buf, len, 0) < 0) {
#else
      if (write(d->ident_sock, buf, len) != len) {
        if (errno != EPIPE) /* read end closed (no remote identd) */
#endif
          logerror("ident check write (conned)");

        STATE(d) = CON_ASKNAME;
        break;
      }

      STATE(d) = CON_IDREADING;
      break;

    case CON_IDREADING:
      /* waiting to read */

      if (d->ident_sock != INVALID_SOCKET) {
        FD_ZERO(&fd);
        FD_ZERO(&efd);
        FD_SET(d->ident_sock, &fd);
        FD_SET(d->ident_sock, &efd);
      }

      if ((rc = select(d->ident_sock + 1, &fd, (fd_set *) 0, &efd, &null_time)) == 0)
        break;

      else if (rc < 0) {
        logerror("ident check select (reading)");
        STATE(d) = CON_ASKNAME;
        break;
      }

      if (FD_ISSET(d->ident_sock, &efd)) {
        STATE(d) = CON_ASKNAME;
        break;
      }

      STATE(d) = CON_IDREAD;
      break;

    case CON_IDREAD:
      /* read ready, get the info */

#ifdef CIRCLE_WINDOWS
      if ((len = recv(d->ident_sock, buf, sizeof(buf) - 1, 0)) < 0)
#else
      if ((len = read(d->ident_sock, buf, sizeof(buf) - 1)) < 0)
#endif
//.........这里部分代码省略.........
开发者ID:nawglan,项目名称:ShadowWind,代码行数:101,代码来源:ident.c


示例15: main


//.........这里部分代码省略.........
			do_select = 1;
		}

		if (rb_space(&inbuf) > 0 && err_n_stdin < MAXRETR) {
			FD_SET(STDIN_FILENO, &readfds);
			do_select = 1;
		}

		if (!rb_isempty(&outbuf) && err_n_stdout < MAXRETR) {
			FD_SET(STDOUT_FILENO, &writefds);
			do_select = 1;
		}

		if (!do_select) {
#ifdef DEBUG
			fprintf(stderr, "No I/O job for us, calling waitpid()...\n");
#endif
			while (waitpid(child_pid, &child_exit_status, 0) < 0)
			{
				/* nothing */
			}
			break;
		}

		int select_rc = select(pty_master + 1, &readfds, &writefds, NULL, NULL);
		if (select_rc < 0) {
			perror("select()");
			exit(EX_IOERR);
		}
#ifdef DEBUG
		fprintf(stderr, "select() returned %d\n", select_rc);
#endif

		if (FD_ISSET(STDOUT_FILENO, &writefds)) {
#ifdef DEBUG
			fprintf(stderr, "stdout can be written\n");
#endif
			ssize_t n = rb_write(&outbuf, STDOUT_FILENO);
			if (n <= 0 && n != EINTR && n != EAGAIN)
				err_n_stdout++;
#ifdef DEBUG
			if (n >= 0)
				fprintf(stderr, "%d bytes written into stdout\n", n);
			else
				perror("write(stdout,...)");
#endif
		}

		if (FD_ISSET(pty_master, &writefds)) {
#ifdef DEBUG
			fprintf(stderr, "pty_master can be written\n");
#endif
			ssize_t n = rb_write(&inbuf, pty_master);
			if (n <= 0 && n != EINTR && n != EAGAIN)
				err_n_wpty++;
#ifdef DEBUG
			if (n >= 0)
				fprintf(stderr, "%d bytes written into pty_master\n", n);
			else
				perror("write(pty_master,...)");
#endif
		}

		if (FD_ISSET(STDIN_FILENO, &readfds)) {
#ifdef DEBUG
			fprintf(stderr, "stdin can be read\n");
开发者ID:Surge1223,项目名称:selinux,代码行数:67,代码来源:open_init_pty.c


示例16: main


//.........这里部分代码省略.........
		} else {
			if (recibirConfigUMC(elEstadoActual.sockUmc, &UMCConfig)) {
				log_error("UMC error - No se pudo recibir la configuracion");
				close(unCliente);
				exit(-2);
			}
			agregar_master(elEstadoActual.sockUmc,maximoAnterior);
			log_info("Paginas por proceso:[%d]", UMCConfig.paginasXProceso);
			log_info("Tamanio de pagina:[%d]", UMCConfig.tamanioPagina);

			elEstadoActual.tamanio_paginas = UMCConfig.tamanioPagina;
		}
		liberarHeaderIPC(unHeaderIPC);
	} else {
		log_error("No se pudo conectar a la UMC");
		elEstadoActual.salir = 1;
	}

	/*Ciclo Principal del Nucleo*/
	log_info(".............................................................................");
	log_info("..............................Esperando Conexion.............................\n\n");
	fflush(stdout);

	while (elEstadoActual.salir == 0) {
		read_fds = fds_master;

		if (seleccionar(elEstadoActual.fdMax, &read_fds, 0) == -1) {
			log_error("Error Preparando el Select");
			break;
		}

		for (unSocket = 0; unSocket <= elEstadoActual.fdMax; unSocket++) {

			if (FD_ISSET(unSocket, &read_fds)) {
				/*Nueva conexion*/
				if (unSocket == elEstadoActual.sockEscuchador) {
					unCliente = aceptar(elEstadoActual.sockEscuchador, &addressAceptado);
					unHeaderIPC = nuevoHeaderIPC(QUIENSOS);
					if (!enviarHeaderIPC(unCliente, unHeaderIPC)) {
						log_error("Cliente Handshake error - No se puede enviar el mensaje QUIENSOS");
						liberarHeaderIPC(unHeaderIPC);
						close(unCliente);
						break;/*Sale del for*/
					}
					liberarHeaderIPC(unHeaderIPC);
					unHeaderIPC = nuevoHeaderIPC(ERROR);
					if (!recibirHeaderIPC(unCliente, unHeaderIPC)) {
						log_error("Cliente Handshake error - No se puede recibir el mensaje");
						liberarHeaderIPC(unHeaderIPC);
						close(unCliente);
						break;/*Sale del for*/
					}

					/*Identifico quien se conecto y procedo*/
					switch (unHeaderIPC->tipo) {
					case CONNECTCONSOLA:
						stHeaderSwitch = nuevoHeaderIPC(OK);
						if (!enviarHeaderIPC(unCliente, stHeaderSwitch)) {
							log_error("Handshake Consola - No se pudo enviar el OK");
							liberarHeaderIPC(stHeaderSwitch);
							close(unCliente);
							break;/*Sale del switch*/
						}
						liberarHeaderIPC(stHeaderSwitch);
						log_info("Nueva consola conectada");
						agregarSock = 1;
开发者ID:nicolas-alejandro-pini,项目名称:tp-2016-1c-WorstPractices,代码行数:67,代码来源:Nucleo.c


示例17: main


//.........这里部分代码省略.........
    if(state == STATE_STOPPED) {
      if(cmd == CMD_NONE)
	cmd = wait_for_cmd(&c);

      if(cmd == CMD_START) {
	state = STATE_STARTED;
	if(ipcio_open(&data_block,'W') < 0)
	  exit(1);
	fprintf(stderr,"after ipcio_open, W\n");
	cmd = CMD_NONE;
      }
      else if(cmd == CMD_EVENT) {
	fprintf(stderr, "Writer: ignored CMD_EVENT in STATE_STOPPED.\n");
	cmd = CMD_NONE;
      }
      else if(cmd == CMD_STOP) {
	fprintf(stderr, "Writer: ignored CMD_STOP in STATE_STOPPED.\n");
	cmd = CMD_NONE;
      }
      else if(cmd == CMD_QUIT) {
	shutdown(c.rqst,2);
	return 0;
      }
    }
    
    //if state is STARTED, poll the command listening socket and the VDIF raw data socket
    if(state == STATE_STARTED) {
      FD_ZERO(&readfds);
      FD_SET(c.rqst, &readfds);
      FD_SET(raw.svc, &readfds);
      select(maxsock+1,&readfds,NULL,NULL,&tv);
      
      //if input is waiting on listening socket, read it
      if(FD_ISSET(c.rqst,&readfds)) {
	cmd = wait_for_cmd(&c);
      }

      if(cmd == CMD_EVENT) {
	//close data block
	if(ipcio_close(&data_block) < 0)
	  exit(1);
	fprintf(stderr,"after ipcio_close\n");
	
	//dump DB to file
	currt = time(NULL);
	tmpt = localtime(&currt);
	strftime(currt_string,sizeof(currt_string), "%Y%m%d_%H%M%S", tmpt);
	*(currt_string+15) = 0;
	sprintf(eventfile,"%s/%s%s_%s_ev.out",EVENTDIR,starthost,dev,currt_string);
	
	if((evfd = fopen(eventfile,"w")) == NULL) {
	  fprintf(stderr,"Writer: Could not open file %s for writing.\n",eventfile);
	}
	else {
	  event_to_file(&data_block,evfd);
	  fclose(evfd);
	}

	//Get pending commands, resume writing to ring buffer if there are none
	FD_ZERO(&readfds);
	FD_SET(c.rqst, &readfds);
	FD_SET(raw.svc, &readfds);
	select(maxsock+1,&readfds,NULL,NULL,&tv);

	state = STATE_STOPPED;
	if(FD_ISSET(c.rqst,&readfds)) {
开发者ID:juliadeneva,项目名称:vlite-psrdada,代码行数:67,代码来源:writer.c


示例18: select_loop

static void select_loop(libvchan_t *vchan)
{
    fd_set select_set;
    fd_set wr_set;
    int max_fd;
    int ret;
    int vchan_fd;
    sigset_t selectmask;
    struct timespec zero_timeout = { 0, 0 };
    struct timespec select_timeout = { 10, 0 };
    struct buffer stdin_buf;

    sigemptyset(&selectmask);
    sigaddset(&selectmask, SIGCHLD);
    sigprocmask(SIG_BLOCK, &selectmask, NULL);
    sigemptyset(&selectmask);
    buffer_init(&stdin_buf);
    /* remember to set back to blocking mode before closing the FD - this may
     * be not the only copy and some processes may misbehave when get
     * nonblocking FD for input/output
     */
    set_nonblock(local_stdin_fd);

    for (;;) {
        vchan_fd = libvchan_fd_for_select(vchan);
        FD_ZERO(&select_set);
        FD_ZERO(&wr_set);
        FD_SET(vchan_fd, &select_set);
        max_fd = vchan_fd;
        if (local_stdout_fd != -1 &&
                (size_t)libvchan_buffer_space(vchan) > sizeof(struct msg_he 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ FD_SET函数代码示例发布时间:2022-05-30
下一篇:
C++ FD_CLR函数代码示例发布时间: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