Example #1
0
DWORD serverThread(void* ptr) {
#else
void* serverThread(void *ptr) {
#endif
	char buffer[2048];
	int length;
	int result;

	do {
		int ms = qbTickCount();
		
		LOCK(lock);
		length=recvPacket(buffer);
		if(length>0) {
			result=processServerPacket((unsigned char *)buffer,length);
			cs->timestamp=_GetTickCount();
		} else {
			result=0;
		}
		UNLOCK(lock);

		int elapsed = qbTickCount() - ms;
		throttle( elapsed, QB_MIN_FRAMETIME );
		
	} while(result==0 && ! kill_server_thread);
	if(online) {
		qbLog("*** Server Disconnected ***");
	}
	online=false;
	return 0;
}
Example #2
0
Rover::Rover(void) :
    param_loader(var_info),
    channel_steer(nullptr),
    channel_throttle(nullptr),
    channel_learn(nullptr),
    DataFlash{FIRMWARE_STRING},
    in_log_download(false),
    modes(&g.mode1),
    L1_controller(ahrs),
    nav_controller(&L1_controller),
    steerController(ahrs),
    mission(ahrs,
            FUNCTOR_BIND_MEMBER(&Rover::start_command, bool, const AP_Mission::Mission_Command&),
            FUNCTOR_BIND_MEMBER(&Rover::verify_command_callback, bool, const AP_Mission::Mission_Command&),
            FUNCTOR_BIND_MEMBER(&Rover::exit_mission, void)),
    num_gcs(MAVLINK_COMM_NUM_BUFFERS),
    ServoRelayEvents(relay),
#if CAMERA == ENABLED
    camera(&relay),
#endif
#if MOUNT == ENABLED
    camera_mount(ahrs, current_loc),
#endif
    control_mode(INITIALISING),
    ground_start_count(20),
    throttle(500),
#if FRSKY_TELEM_ENABLED == ENABLED
    frsky_telemetry(ahrs, battery, sonar),
#endif
    home(ahrs.get_home()),
    G_Dt(0.02)
{
}
Example #3
0
Rover::Rover(void) :
    param_loader(var_info),
    channel_steer(nullptr),
    channel_throttle(nullptr),
    channel_learn(nullptr),
    DataFlash{FIRMWARE_STRING, g.log_bitmask},
    modes(&g.mode1),
    L1_controller(ahrs, nullptr),
    nav_controller(&L1_controller),
    steerController(ahrs),
    mission(ahrs,
            FUNCTOR_BIND_MEMBER(&Rover::start_command, bool, const AP_Mission::Mission_Command&),
            FUNCTOR_BIND_MEMBER(&Rover::verify_command_callback, bool, const AP_Mission::Mission_Command&),
            FUNCTOR_BIND_MEMBER(&Rover::exit_mission, void)),
    ServoRelayEvents(relay),
#if CAMERA == ENABLED
    camera(&relay),
#endif
#if MOUNT == ENABLED
    camera_mount(ahrs, current_loc),
#endif
    control_mode(INITIALISING),
    throttle(500),
#if FRSKY_TELEM_ENABLED == ENABLED
    frsky_telemetry(ahrs, battery, rangefinder),
#endif
    do_auto_rotation(false),
    home(ahrs.get_home()),
    G_Dt(0.02f)
{
}
Example #4
0
void gets2c()           // get updates from the server
{
    ENetEvent event;
    if(!clienthost) return;
    if(connpeer && totalmillis/3000 > connmillis/3000)
    {
        conoutf("attempting to connect...");
        connmillis = totalmillis;
        ++connattempts;
        if(connattempts > 3)
        {
            conoutf("\f3could not connect to server");
            abortconnect();
            return;
        }
    }
    while(clienthost && enet_host_service(clienthost, &event, 0)>0)
    switch(event.type)
    {
        case ENET_EVENT_TYPE_CONNECT:
            disconnect(false, false);
            localdisconnect(false);
            curpeer = connpeer;
            connpeer = NULL;
            conoutf("connected to server");
            throttle();
            if(rate) setrate(rate);
            game::gameconnect(true);
            break;

        case ENET_EVENT_TYPE_RECEIVE:
            if(discmillis) conoutf("attempting to disconnect...");
            else localservertoclient(event.channelID, event.packet);
            enet_packet_destroy(event.packet);
            break;

        case ENET_EVENT_TYPE_DISCONNECT:
            extern const char *disc_reasons[10]; /* because gcc 4.2 is retarded */
            if(event.data>=DISC_NUM) event.data = DISC_NONE;
            if(event.peer==connpeer)
            {
                conoutf("\f3could not connect to server");
                abortconnect();
            }
            else
            {
                if(!discmillis || event.data) conoutf("\f3server network error, disconnecting (%s) ...", disc_reasons[event.data]);
                disconnect();
            }
            return;

        default:
            break;
    }
}
Example #5
0
void gets2c()           // get updates from the server
{
    ENetEvent event;
    if(!clienthost) return;
    if(connpeer && totalmillis/3000 > connmillis/3000)
    {
        connmillis = totalmillis;
        ++connattempts;
        if(connattempts > 3)
        {
            conoutft(CON_MESG, "\frcould not connect to server");
            connectfail();
            return;
        }
        else conoutft(CON_MESG, "\faconnection attempt %d", connattempts);
    }
    while(clienthost && enet_host_service(clienthost, &event, 0)>0)
    switch(event.type)
    {
        case ENET_EVENT_TYPE_CONNECT:
            disconnect(1);
            curpeer = connpeer;
            connpeer = NULL;
            conoutft(CON_MESG, "\fgconnected to server");
            throttle();
            if(rate) setrate(rate);
            client::gameconnect(true);
            break;

        case ENET_EVENT_TYPE_RECEIVE:
            if(discmillis) conoutft(CON_MESG, "\faattempting to disconnect...");
            else localservertoclient(event.channelID, event.packet);
            enet_packet_destroy(event.packet);
            break;

        case ENET_EVENT_TYPE_DISCONNECT:
            if(event.data>=DISC_NUM) event.data = DISC_NONE;
            if(event.peer==connpeer)
            {
                conoutft(CON_MESG, "\frcould not connect to server");
                connectfail();
            }
            else
            {
                if(!discmillis || event.data) conoutft(CON_MESG, "\frserver network error, disconnecting (%s) ...", disc_reasons[event.data]);
                disconnect();
            }
            return;

        default:
            break;
    }
}
Example #6
0
int main(int argc, char ** argv) 
{
    /**** In Defaults.h ****/
    struct global_t global;
    struct const_t constant;
    struct stats_t stats;
    struct display_t dpy;
    /***********************/

    /***************** In Initialize.h *****************/
    init(&global, &constant, &stats, &dpy, &argc, &argv);
    /***************************************************/

    // Each process starts a loop to run the simulation 
    // for the specified number of days
    for(global.current_day = 0; global.current_day <= constant.total_number_of_days; 
        global.current_day++)
    {
        /****** In Infection.h ******/
        find_infected(&global);
        /****************************/

        /**************** In Display.h *****************/
        #if defined(X_DISPLAY) || defined(TEXT_DISPLAY)

        do_display(&global, &constant, &dpy);

        throttle(&constant);

        #endif
        /***********************************************/

        /************** In Core.h *************/
        move(&global, &constant);       

        susceptible(&global, &constant, &stats);

        infected(&global, &constant, &stats);

        update_days_infected(&global, &constant);
        /**************************************/
    }

    /******** In Finialize.h ********/
    show_results(&global, &stats);

    cleanup(&global, &constant, &dpy);
    /********************************/

    exit(EXIT_SUCCESS);
}
Example #7
0
/**
 * Main function.
 */
int main(int argc, char **argv)
{
	const char *config_fn, *pipe_fn;

	// Read arguments from command line, or take the defaults
	config_fn = (argc > 1) ? argv[1] : "throttle.conf";
	pipe_fn = (argc > 2) ? argv[2] : "pipe";

	// Block SIGINT, SIGQUIT, SIGTERM - we're going to wait for them explicitly.
	sigset_t signals;
	sigemptyset(&signals);
	sigaddset(&signals, SIGINT);
	sigaddset(&signals, SIGQUIT);
	sigaddset(&signals, SIGTERM);
	sigprocmask(SIG_BLOCK, &signals, nullptr);

	const struct timespec wait_time{wait, 0};

	try {
		// create Throttle object
		Throttle throttle(config_fn, pipe_fn);

		// Run the feedback loop
		do
			throttle();
		while (sigtimedwait(&signals, nullptr, &wait_time) == -1);
	}
	catch (const std::runtime_error& ex) {
		std::cerr << "Error: " <<  ex.what() << std::endl;
		return 1;
	}

	DEBUG_PRINT("[Main] Successful shutdown");

	return 0;
}
Controller::Controller()
{
	turnProportionalGain = 1.0f; //converts offset from camera to turn duty cycle
	throttleProportionalGain = 10.0f; // converts offset in the y direction to throttle
	sideProportionalGain = 1.0f;
	hover_throttle = 1.54;
	lower_altitude = 0;
  	//initialize all controls to neutral
	turn(1.5);
	forward(1.48);
	side(1.59);
	throttle(1.09);
	isStarted = 0;
	time_lift = 0;
}
TEST_CASE test_msg_throttle()
{
    ThrottledMsgLogger throttle("Test", 2.0);
    // OK to print one message.
    throttle.LOG_MSG("Hello!\n");
    // Then, messages are discouraged...
    TEST(!throttle.isPermitted());
    throttle.LOG_MSG("Hello, too!\n");
    throttle.LOG_MSG("Hello, too!\n");
    throttle.LOG_MSG("Hello, too!\n");
    throttle.LOG_MSG("Hello, too!\n");
    throttle.LOG_MSG("Hello, too!\n");

    TEST_MSG(1, "waiting a little bit...");
    epicsThreadSleep(2.5);
    throttle.LOG_MSG("Hello again\n");

    TEST_OK;
}
Example #10
0
bool http_t::get( std::string& result,
                  const std::string& url,
                  const std::string& confirmation,
                  int64_t timestamp,
                  int throttle_seconds )
{
  static void* mutex = 0;

  thread_t::mutex_lock( mutex );

  result.clear();

  bool success = cache_get( result, url, timestamp );

  if ( ! success )
  {
    util_t::printf( "@" ); fflush( stdout );
    throttle( throttle_seconds );
    std::string encoded_url;
    success = download( result, format( encoded_url, url ) );

    if ( success )
    {
      if ( confirmation.size() > 0 && ( result.find( confirmation ) == std::string::npos ) )
      {
        //util_t::printf( "\nsimulationcraft: HTTP failed on '%s'\n", url.c_str() );
        //util_t::printf( "%s\n", ( result.empty() ? "empty" : result.c_str() ) );
        fflush( stdout );
        success = false;
      }
      else
      {
        cache_set( url, result, timestamp );
      }
    }
  }

  thread_t::mutex_unlock( mutex );

  return success;
}
Example #11
0
int main(int argc, char ** argv) {
	int count;
	struct life_t life;

	init(&life, &argc, &argv);

	while (1) {
		if (life.do_display)
			do_draw(&life);

		copy_bounds(&life);

		eval_rules(&life);

		update_grid(&life);

		throttle(&life);

	}

	cleanup(&life);

	exit(EXIT_SUCCESS);
}
Example #12
0
/*
========================================================================
emulate:	This routine contains the main loop that handles active 
			emulation and maintenance tasks.
========================================================================
*/
void emulate(void)
{
	unsigned int	i,j;
	unsigned int	v;
	int				nxtmaint=1;
	int				ins;

	starttime=msclock();
	lock_remote();
	while(!gExitApp) 
	{
		/* Run appropriate emulation loop base on ReMem support */
		if (gReMem)
			while (!gExitLoop)
			{
				/* Check for active debug monitor windows */
				if (gDebugActive)
				{
					do_debug_stuff();
					if (gExitLoop) 
						break;
				}

				/* Instruction emulation contained in header file */
				#undef NO_REMEM
				#include "cpu.h"
				#include "do_instruct.h"

				// Check if next inst is SIM
				if ((get_memory8(PC) == 0xF3) || ((IM & 0x2A) == 0x20) ||
					((IM & 0x4C) == 0x40))
				{
					check_interrupts();
				}

				// Check for return from interrupt
				if (gIntActive)
				{
					if (SP == gIntSP)
						gIntActive = FALSE;
				}
				if (gSingleStep)
				{
					if (!gIntActive)
					{
						gSingleStep = 0;
					}
				}

				/* Do maintenance tasks (Windows events, interrupts, etc.) */
#ifdef __APPLE__
				if(!(--nxtmaint)) 
#else
				if(!(--nxtmaint & 0x3FF)) 
#endif
				{
					unlock_remote();
					gOsDelay = nxtmaint == 0;
					throttle(cycle_delta);
					maint();
					ser_poll();
					check_interrupts();
					if (gOsDelay)
						nxtmaint=gMaintCount;
					lock_remote();
				}
#if 0
				exec_remem_instruction();

					if (gExitLoop) 
						break;
#endif
			}

		if (!gReMem)
		{
			while (!gExitLoop)
			{
				/* Check for active debug monitor windows */
				if (gDebugActive)
				{
					do_debug_stuff();
					if (gExitLoop)
						break;
				}

				/* Instruction emulation contained in header file */
				#define NO_REMEM
				#include "cpu.h"
				#include "do_instruct.h"

				// Check if next inst is SIM or RS-232 waiting
				if ((get_memory8(PC) == 0xF3) || ((IM & 0x2A) == 0x20) ||
					((IM & 0x4C) == 0x40))
				{
					check_interrupts();
				}

				// Check for return from interrupt
				if (gIntActive)
				{
					if (SP == gIntSP)
						gIntActive = FALSE;
				}
				if (gSingleStep)
				{
					if (!gIntActive)
					{
						gSingleStep = 0;
					}
				}

				/* Do maintenance tasks (Windows events, interrupts, etc.) */
#ifdef __APPLE__
				if(!(--nxtmaint)) 
#else
				if(!(--nxtmaint & 0x3FF)) 
#endif
				{
					unlock_remote();
					gOsDelay = nxtmaint == 0;
					throttle(cycle_delta);
					maint();
					ser_poll();
					check_interrupts();
					if (gOsDelay)
						nxtmaint=gMaintCount;
					lock_remote();
				}
			}
		}

		gExitLoop = 0;
	}
	unlock_remote();
}
Example #13
0
    int n = client::otherclients();
    if(n && msg) conoutft(CON_MESG, "\froperation not available with other clients");
    return n > 0;
}

void setrate(int rate)
{
   if(!curpeer) return;
    enet_host_bandwidth_limit(clienthost, rate*1024, rate*1024);
}

VARF(0, rate, 0, 0, 1024, setrate(rate));

void throttle();

VARF(0, throttle_interval, 0, 5, 30, throttle());
VARF(0, throttle_accel, 0, 2, 32, throttle());
VARF(0, throttle_decel, 0, 2, 32, throttle());

void throttle()
{
    if(!curpeer) return;
    ASSERT(ENET_PEER_PACKET_THROTTLE_SCALE==32);
    enet_peer_throttle_configure(curpeer, throttle_interval*1000, throttle_accel, throttle_decel);
}

bool connected(bool attempt, bool local)
{
    return curpeer || (attempt && connpeer) || (local && haslocalclients());
}
Example #14
0
void Engine::arm()
{
	throttle(1);
	sleep(2, second);
	throttle(0);
}
Example #15
0
bool http_t::get( std::string&       result,
                  const std::string& url,
                  cache::behavior_t  caching,
                  const std::string& confirmation,
                  int                throttle_seconds )
{
    result.clear();

    std::string encoded_url;
    format( encoded_url, url );

    auto_lock_t lock( cache_mutex );

    url_cache_entry_t& entry = url_db[ encoded_url ];

    if ( HTTP_CACHE_DEBUG )
    {
        std::ofstream http_log( "simc_http_log.txt", std::ios::app );
        std::ostream::sentry s( http_log );
        if ( s )
        {
            http_log << cache::era() << ": get(\"" << url << "\") [";

            if ( entry.validated != cache::INVALID_ERA )
            {
                if ( entry.validated >= cache::era() )
                    http_log << "hot";
                else if ( caching != cache::CURRENT )
                    http_log << "warm";
                else
                    http_log << "cold";
                http_log << ": (" << entry.modified << ", " << entry.validated << ')';
            }
            else
                http_log << "miss";
            if ( caching != cache::ONLY &&
                    ( entry.validated == cache::INVALID_ERA ||
                      ( caching == cache::CURRENT && entry.validated < cache::era() ) ) )
                http_log << " download";
            http_log << "]\n";
        }
    }

    if ( entry.validated < cache::era() && ( caching == cache::CURRENT || entry.validated == cache::INVALID_ERA ) )
    {
        if ( caching == cache::ONLY )
            return false;

        util_t::printf( "@" );
        fflush( stdout );
        throttle( throttle_seconds );

        if ( ! download( entry, encoded_url ) )
            return false;

        if ( HTTP_CACHE_DEBUG && entry.modified < entry.validated )
        {
            std::ofstream http_log( "simc_http_log.txt", std::ios::app );
            http_log << cache::era() << ": Unmodified (" << entry.modified << ", " << entry.validated << ")\n";
        }

        if ( confirmation.size() && ( entry.result.find( confirmation ) == std::string::npos ) )
        {
            //util_t::printf( "\nsimulationcraft: HTTP failed on '%s'\n", url.c_str() );
            //util_t::printf( "%s\n", ( result.empty() ? "empty" : result.c_str() ) );
            //fflush( stdout );
            return false;
        }
    }

    result = entry.result;
    return true;
}
Example #16
0
void PowerModel::calcStats(uint64_t timeinterval, bool keepPower, FlowID fid)
/* calcStats {{{1 */
{
    // This is called through sampler. So the power/thermal
    // simulator are called explicitly rather than periodically by
    // a timer.
    //
    //need to sync stats first

    energyBundle->setFreq(getFreq());

    if (!keepPower) {     // Calculate new Power
        updateActivity(timeinterval, fid);
        // Dump eSESC performance counters to file
        if (logfile)
            printStatus();

        mcpatWrapper->calcPower(activity, energyBundle, &clockInterval);

        //Turbo
        if (enableTurbo)
            updateTurboState();
        //FIXME: else i should copy lkg to scaled lkg

        //dumpTotalPower("totalp");


        if (doPowPred) {
            updatePowerHist();
            loadPredPower();
        }
    }

    //dumpTotalPower("totalpf");




    uint32_t throttleLength = 0;
    if (doTherm) {
        if (energyBundle->cntrs.size()>0) {
            sescThermWrapper->calcTemp(energyBundle, temperatures, timeInterval, throttleLength);
        }
    }

    updatePowerGStats();
    dumpTotalPower("totalpTh");
    //double tp = getLastTotalPower();
#ifdef ENABLE_CUDA
    double ed = getCurrentED();
    //printf("total Power TH:%f, ED:%f, Vol:%f  timeinterval=%lu\n", tp, ed, volNTC, (long unsigned int) timeinterval);
#else
    //printf("total Power TH:%f, Vol:%f  timeinterval=%lu\n", tp, volNTC, (long unsigned int) timeinterval);
#endif

    // Thermal Throttling
    throttle(fid, throttleLength);
    updatePowerTime(timeInterval);

    if (dumppwth && logpwrdyn/* && tc > 0*/) {
        dumpDynamic();
        if (logprf)
            dumpPerf(false);
    }
}
Example #17
0
int main (int argc, char *argv[])
{
   size_t count = 0;    /* Forever */
   char *iface = NULL;  /* No default iface, rely on routing table. */
   int rate = 500;
   int qos = 0;                 /* No Prio */
   int sd, dly, c;
   size_t len = 22;             /* Default to 64 byte packets */
   int payload = 0xA5;
   struct sockaddr_in sin;
   struct option long_options[] = {
      /* {"verbose", 0, 0, 'V'}, */
      {"verbose", 0, 0, 'V'},
      {"version", 0, 0, 'v'},
      {"interface", 1, 0, 'i'},
      {"count", 1, 0, 'c'},
      {"tos", 1, 0, 'Q'},
      {"rate", 1, 0, 'r'},
      {"size", 1, 0, 's'},
      {"payload", 1, 0, 'p'},
      {"help", 0, 0, '?'},
      {0, 0, 0, 0}
    };

   progname = argv[0];

   while ((c = getopt_long (argc, argv, "i:c:p:Q:r:s:vVh?", long_options, NULL)) != EOF)
   {
      switch (c)
      {
         case 'i':              /* --interface */
            iface = strdup (optarg);
            DEBUG("Iface: %s\n", iface);
            break;

         case 'c':              /* --count */
            count = strtoul (optarg, NULL, 0);
            DEBUG("Count: %zu\n", count);
            break;

         case 'Q':              /* --tos */
            qos = strtoul (optarg, NULL, 0);
            DEBUG("QoS: %d\n", qos);
            break;

         case 'r':              /* --rate */
            rate = strtoul (optarg, NULL, 0);
            DEBUG("Rate: %d packets/second\n", rate);
            break;

         case 's':              /* --size */
            len = strtoul (optarg, NULL, 0);
            DEBUG("Size: %zu bytes payload\n", len);
            /* Adjust for MAC+UDP header */
            len = len > 64 ? len - 42 : 22; /* At least 64 bytes */
            break;

         case 'p':              /* --payload */
            payload = strtoul (optarg, NULL, 0);
            DEBUG("Size: %d bytes payload\n", payload);
            break;

         case 'v':              /* --version */
            printf ("%s %s\n", doc, program_version);
            return 0;

         case 'V':              /* --verbose */
            verbose = 1;
            break;

         case 'h':
         case '?':
         default:
            return usage ();
      }
   }

   /* At least one argument needed. */
   if (argc < 2)
   {
      return usage();
   }

   DEBUG("Broadcast address %s, size %zu\n", argv[optind], len);
   
   sd = udp_socket_init (iface, UDP_PORT, argv[optind], &sin, qos);
   if (sd < 0)
   {
      if (iface)
      {
         free (iface);
      }
      return 1;
   }

   dly = throttle_calibrate (rate);

   while (1)
   {
      const char data[1458] = { [0 ... 1457] = payload };

      if (sendto (sd, data, len, 0, (struct sockaddr *)&sin, sizeof (sin)) < 0)
      {
         perror ("Failed sending packet");
         if (iface)
         {
            free (iface);
         }
         return 1;
      }

      throttle (dly);
   }
Example #18
0
File: snget.c Project: liu-chong/sn
int main (int argc, char **argv)
{
   char optdebugbuf[7];
   int n, mark;
   char *cp;

   progname = ((cp = strrchr(argv[0], '/')) ? cp + 1 : argv[0]);

   while ((n = opt_get(argc, argv, "pthcmo")) > -1)
      switch (n)
      {
         case 'd':
            if (++debug < 6)
	    {
               if (!optdebug)
                  strcpy(optdebug = optdebugbuf, "-d");
               else
                  strcat(optdebug, "d");
            }
            break;
         case 'V': version(); _exit(0);
         case 't':
            if (!opt_arg)
               usage();
            LOG("option \"-t %s\" no longer supported", opt_arg);
            break;
         case 'p':
            if (!opt_arg)
               usage();
            concurrency = strtoul(opt_arg, &cp, 10);
            if (concurrency > MAX_CONCURRENCY || concurrency <= 0 || *cp)
               fail(1, "Bad value for concurrency option -p");
            break;
         case 'h':
            if (!opt_arg)
               usage();
            throttlerate = strtoul(opt_arg, &cp, 10);
            if (throttlerate < 0)
               fail(1, "Bad value for throttle option -h");
            break;
         case 'c':
            if (!(optpipelining = opt_arg))
               usage();
            if (strtoul(optpipelining, &cp, 10) < 0 || *cp)
               fail(1, "Bad value for pipeline option -c");
            break;
         case 'm':
            if (!(optmax = opt_arg))
               usage();
            if (strtoul(optmax, &cp, 10) <= 0 || *cp)
               fail(1, "Bad value for max-prime-articles option -m");
            break;
         case 'P':
            optlogpid = TRUE;
            log_with_pid();
            break;
         default:
            usage();
      }
   close(0);
   open("/dev/null", O_RDONLY);
   /* snag 6 and 7 so we can dup onto them */
   if (-1 == dup2(2, 6) || -1 == dup2(2, 7) || -1 == dup2(2, 1))
      fail(2, "Unable to dup standard error:%m");

   parameters(TRUE);
   if (-1 == chdir(snroot))
      fail(2, "chdir(%s):%m", snroot);
   init();
   if (-1 == set_path_var())
      fail(2, "No memory");

   n = 0;
   if (opt_ind == argc)
   {
      DIR *dir;
      struct dirent *dp;
      struct stat st;
      char ch;

      if (!(dir = opendir(".")))
         fail(2, "opendir(%s):%m", snroot);
      while ((dp = readdir(dir)))
         if (is_valid_group(dp->d_name))
            if (-1 == readlink(dp->d_name, &ch, 1)) /* no symlinks */
               if (0 == statf(&st, "%s/.outgoing", dp->d_name))
                  if (S_ISDIR(st.st_mode))
                     if (add(dp->d_name) > -1)   /* NB: add() from get.c */
                        n++;
      closedir(dir);
   }
   else
   {
      debug++;
      for (; opt_ind < argc; opt_ind++)
         if (add(argv[opt_ind]) > -1)
            n++;
      debug--;
   }

   if (n == 0)
      fail(0, "No groups to fetch");

   for (mark = 0; jobs_not_done(); mark++)
   {
      struct timeval tv;
      fd_set rset;
      int max;

      while (sow() == 0)   /* Start some jobs */
         ;
      FD_ZERO(&rset);
      if (throttlerate)
      {
         max = throttle_setfds(&rset);
         if (sigusr)
         {
            sigusr = FALSE;
            LOG("throttling at %d bytes/sec", throttlerate);
         }
      }
      else
         max = -1;
      
      tv.tv_sec = 1;
      tv.tv_usec = 0;
      if (select(max + 1, &rset, NULL, NULL, &tv) > 0)
         if (throttlerate)
            throttle(&rset);
      
      if (sigchld || 1 == mark % 10)
      {
         sigchld = FALSE;
         while (reap() == 0)
            ;
      }
   }
   quit();
   _exit(0);
}
Example #19
0
void gets2c()           // get updates from the server
{
    ENetEvent event;
    if(!clienthost) return;
    if(connpeer && totalmillis/3000 > connmillis/3000)
    {
        conoutf("attempting to connect...");
        connmillis = totalmillis;
        ++connattempts; 
        if(connattempts > 3)
        {
            conoutf("\f3could not connect to server");
            abortconnect();
            return;
        }
    }
    while(clienthost && enet_host_service(clienthost, &event, 0)>0)
    switch(event.type)
    {
        case ENET_EVENT_TYPE_CONNECT:
            disconnect(false, false); 
            localdisconnect(false);
            curpeer = connpeer;
            connpeer = NULL;
            conoutf("connected to server");
            throttle();
            if(GETIV(rate)) setrate(GETIV(rate));
            game::gameconnect(true);
            break;
         
        case ENET_EVENT_TYPE_RECEIVE:
#if CLIENT // INTENSITY
            if(discmillis) conoutf("attempting to disconnect...");
            else localservertoclient(event.channelID, event.packet);
            enet_packet_destroy(event.packet);
#else // SERVER
            assert(0);
#endif
            break;

        case ENET_EVENT_TYPE_DISCONNECT:
//            LogicSystem::init(); // INTENSITY: Not sure about this...?

            extern const char *disc_reasons[];
            if(event.data>=DISC_NUM) event.data = DISC_NONE;
            if(event.peer==connpeer)
            {
                conoutf("\f3could not connect to server");
                abortconnect();
            }
            else
            {
                if(!discmillis || event.data) conoutf("\f3server network error, disconnecting (%s) ...", disc_reasons[event.data]);
                disconnect();
            }
            return;

        default:
            break;
    }
}