Esempio n. 1
0
/*
 * Idea for implementing parsing:
 * Stack of lists of automatons.
 * For every character in the regex:
 * - if char == (, then push in another list
 * - if char == ), then pop a list, create union
 * of all automatons in the popped list, char++,
 * add the resulting automaton to the list at the head
 * - if char == |, then add a new automaton to the list
 * - otherwise, concatenate char to the last automaton
 * in the current list
 *
 * Time: O(strlen(regex)), which should be minimal.
 */
void build_bs_helper(temp_automaton& a, char* regex) {
	if (regex == 0) {
		return;
	}
	Stack<Queue<temp_automaton>> s;
	add_queue(s);
	int i = 0;
	while (regex[i] != 0) {
		if (regex[i] == '(') {
			add_queue(s);
		} else if (regex[i] == ')') {
			i++; // Because of the *
			Queue<temp_automaton> q;
			s.pop(q);
			temp_automaton first;
			q.pop(first);
			while (!q.isEmpty()) {
				temp_automaton next;
				q.pop(next);
				concat(first, next);
			}
		} else {
			// Concatenate regex[i] to s.peek().peek_last(),
			// i.e. to the last automaton.
			temp_automaton a;
			build_bs_char(a, regex[i]);
			concat(s.peek().peek_last(), a);
		}
		i++;
	}
}
Esempio n. 2
0
void QContentHubServer::push_queue_nowait(msgpack::rpc::request &req, const std::string &name, const std::string &obj)
{
    queue_map_t &qmap = q_map.unsafe_ref();

    queue_map_it_t it = qmap.find(name);
    if (it == qmap.end()) {
        int ret = add_queue(name, DEFAULT_QUEUE_CAPACITY);
        if (ret == QCONTENTHUB_ERROR) {
            req.result(ret);
        } else {
            push_queue(req, name, obj);
        }
    } else {
        queue_t *q = it->second;
        pthread_mutex_lock(&q->lock);
        if ((int)q->str_q.size() > q->capacity) {
            pthread_mutex_unlock(&q->lock);
            req.result(QCONTENTHUB_AGAIN);
        } else {
            q->str_q.push(obj);
            pthread_cond_signal(&q->not_empty);
            pthread_mutex_unlock(&q->lock);
            req.result(QCONTENTHUB_OK);
        }
    }
}
Esempio n. 3
0
void test(){
	LL tab1 = NULL;
	int tab[N]={12,2,0,3,55,88,42,26,17,8};
	int i;
	for (i=9;i>=0;i--){
		add_queue(&tab1,tab[i]);
	}
	display_size(tab1);
	printf("\n");
	print_inc(tab1);
	printf("\n");

	printf("Valeur max de la liste: %d\n", maximum(tab1));
	printf("\n");
	printf("Valeur min de la liste: %d\n", minimum(tab1));
	printf("\n");

	printf("Tri de la liste: \n");
	sort_ascending(tab1);
	printf("\n");

	if(delete_list(tab1)==NULL){
        printf("Linked list has been deleted.\n");
    }
}
Esempio n. 4
0
void init_attack( char_data* ch, char_data* victim )
{
  event_data* event;

  if( victim != NULL )
    ch->aggressive += victim;

  if( ch->active.time != -1 ) 
    return;

  for( int i = 0; i < ch->events.size; i++ )
    if( ch->events[i]->func == execute_leap )
      return;

  if( victim == NULL ) {
    if( is_empty( ch->aggressive ) )
      return;
    victim = ch->aggressive[0];
    }

  event          = new event_data( execute_leap, ch );
  event->pointer = (void*) victim; 

  add_queue( event, 20 );
}
Esempio n. 5
0
void queue_package(pkgstate* state, stringptr* packagename, jobtype jt, int force) {
	if(!packagename->size) return;
	sblist* queue = (jt == JT_DOWNLOAD) ? state->dl_queue : state->build_queue;
	if(is_in_queue(packagename, queue)) return;
	
	if(!force && is_installed(state->installed_packages, packagename)) {
		ulz_fprintf(1, "package %s is already installed, skipping %s\n", packagename->ptr, jt == JT_DOWNLOAD ? "download" : "build");
		return;
	}
	
	uint32_t hash = stringptr_hash(packagename);
	pkgdata* pkg = packagelist_get(state->package_list, packagename, hash);
	unsigned i;
	
	if(!pkg) {
		pkg = packagelist_add(state->package_list, packagename, hash);
		get_package_contents(&state->cfg, packagename, pkg);
	}
	
	for(i = 0; i < stringptrlist_getsize(pkg->deps); i++)
		queue_package(state, stringptrlist_get(pkg->deps, i), jt, 0); // omg recursion
	
	if(
		// if sizeof mirrors is 0, it is a meta package
		(jt == JT_DOWNLOAD && stringptrlist_getsize(pkg->mirrors) && !has_tarball(&state->cfg, pkg))
		|| (jt == JT_BUILD && stringptrlist_getsize(pkg->buildscript))
	) {
		add_queue(packagename, queue);
	}
	
}
Esempio n. 6
0
void delay_wander( event_data* event )
{
  char_data*      ch  = (char_data*) event->owner;
  int         wander  = ch->species->wander;
 
  add_queue( event, number_range( wander/10, wander ) );
}
Esempio n. 7
0
void execute_path( event_data* event )
{
  char_data*    ch  = (char_data*) event->owner;
  path_data*  path  = (path_data*) event->pointer;

  for( int i = 0; i < ch->in_room->contents; i++ )
    if( ch->in_room->contents[i] == path->summoner ) 
      goto end_path;

  move_char( ch, path->directions[ path->step++ ], FALSE );

  if( !ch->Is_Valid( ) )
    return;

  if( path->step < path->length ) {
    add_queue( event, 50 );
    return;
    }

  end_path:

  extract( event );

  if( !is_set( &ch->status, STAT_SENTINEL ) )    
    delay_wander( new event_data( execute_wander, ch ) );  
}
Esempio n. 8
0
static void		wait_answer_queue(t_thread_handler *thread_handler, int port, char *scan, int id, char *host)
{
	t_queue		*queue = new_queue(port, IPPROTO_TCP, scan, id, host);

	if (queue) {
		add_queue(queue);
	} else {
		pthread_mutex_unlock(&globals->queue_lock);
	}
}
Esempio n. 9
0
File: cpu.c Progetto: bartklin/irqd
struct cpu_info *
cpu_add_queue(int cpu, struct interface *iface, int queue)
{
    struct cpu_info *ci = cpu_nth(cpu);
    struct if_queue_info *qi = if_queue(iface, queue);

    if (add_queue(ci, qi) < 0)
        return NULL;
    return ci;
}
Esempio n. 10
0
File: cpu.c Progetto: bartklin/irqd
/* assign queue to CPU, select most idle CPU from a cpuset */
struct cpu_info *
cpu_add_queue_lru(struct interface *iface, int queue)
{
    const struct cpuset *set = iface->if_cpuset;
    struct cpu_info *ci = set->cs_cpu_lru_list->data;
    struct if_queue_info *qi = if_queue(iface, queue);

    if (add_queue(ci, qi) < 0)
        return NULL;
    return ci;
}
Esempio n. 11
0
/* Adds a message to the message queue. */
void add_message(char * message, int message_length) {

	pthread_mutex_lock(&mutex);

	if (!is_init || !message || message_length <= 0)
		return;

	string_node * snode = alloc_string_node(message, message_length);
	add_queue(&q, &(snode->node));
	
	pthread_mutex_unlock(&mutex);
}
Esempio n. 12
0
thread_t *
thread_create(void (*function)(void))
{
	DPRINTF("function:%p\n", function);
	thread_t *t = calloc(sizeof(thread_t), 1);
	md_thread_create(t, function);
	add_queue(t);
	DPRINTF("&runq:%p runq.prev:%p runq.next:%p\n", 
		&runq, runq.prev, runq.next);
	DPRINTF("t:%p\n", t);
	return t;
}
Esempio n. 13
0
queue_unit* add_queue(queue_unit *unit, int cfp, char *key) {
    if (unit->next == NULL) {
        unit->next = UNIT_NEW;
        unit->next->pre = unit;
        unit->next->socket_num = cfp;
        unit->next->next = NULL;
        strncpy(unit->next->key, key,KEY_MAX_LEN);
        return unit->next;
    } else {
        return add_queue(unit->next, cfp, key);
    }
}
Esempio n. 14
0
void execute_drown( event_data* event )
{
  char_data* ch = (char_data*) event->owner;

  if( !is_set( ch->affected_by, AFF_WATER_BREATHING ) ) {
    send( ch, "You try to breath but just swallow water.\n\r" );
    send_seen( ch, "%s is drowning!\n\r", ch );
    if( inflict( ch, NULL, 5, "drowning" ) )
      return;
    }

  add_queue( event, number_range( 50, 75 ) );
}
Esempio n. 15
0
void passive_action( char_data* ch )
{
  command_data*   cmd;

  if( ch->cast != NULL ) {
    spell_update( ch );
    return;
    }

  for( ; ; ) {
    if( ( cmd = pop( ch->cmd_queue ) ) == NULL )
      break;
    assign_bit( &ch->status, STAT_ORDERED, cmd->ordered );
    interpret( ch, cmd->string );
    remove_bit( &ch->status, STAT_ORDERED );
    delete cmd;
    if( ch->link != NULL )
      ch->link->idle = 0;
    if( ch->active.time != -1 )
      return;
    }

  check_wimpy( ch );

  if( is_set( ch->affected_by, AFF_ENTANGLED ) ) {
    struggle_web( ch );
    add_queue( &ch->active, 32 );
    return;
    }

  if( ch->position < POS_STANDING
    && ( ch->fighting != NULL
    || !is_empty( ch->aggressive ) ) ) {
    jump_feet( ch );
    add_queue( &ch->active, 32 );
    }    
}
Esempio n. 16
0
void add_path( char_data* ch, char_data* summoner )
{
  path_data*    path;
  event_data*  event;

  if( ( path = make_path( ch->in_room ) ) == NULL )
    return;

  stop_events( ch, execute_path );
  stop_events( ch, execute_wander );

  event          = new event_data( execute_path, ch );
  event->pointer = (void*) path;  
  path->summoner = summoner; 

  add_queue( event, 50 );
}
Esempio n. 17
0
void char_bash( char_data* ch, char_data* victim )
{
  int delay;

  if( victim == ch ) {
    send( ch, "Bashing yourself is not very productive.\n\r" );
    return;
    }

  if( victim->species != NULL ) { 
    if( is_set( &victim->species->act_flags, ACT_NO_BASH ) ) {
      send( ch, "Bashing that does not make sense.\n\r" );
      return;
      }
    if( is_set( &victim->species->act_flags, ACT_GHOST ) ) {
      send( ch, "Bashing a ghost is a completely futile exercise.\n\r" );
      return;
      }
    }

  if( victim->position < POS_FIGHTING ) {
    send( ch, "Your victim is already on the ground!\n\r" );
    return;
    }

  if( victim->Size( ) > ch->Size( )+1 ) {
    send( ch, "%s is way too large for you to successfully bash %s.\n\r",
      victim, victim->Him_Her( ) );
    return;
    }

  if( !can_kill( ch, victim ) )
    return;

  check_killer( ch, victim );
  ch->fighting = victim;
  react_attack( ch, victim );  

  remove_bit( &ch->status, STAT_LEAPING );
  remove_bit( &ch->status, STAT_WIMPY );

  ch->improve_skill( SKILL_BASH );

  delay = bash_attack( ch, victim );
  add_queue( &ch->active, delay );
}
Esempio n. 18
0
void fight_round( char_data* ch )
{
  int time;

  ch->fighting->shown = 1;

  time = ( ch->species != NULL ? mob_round( ch, ch->fighting ) 
    : player_round( ch, ch->fighting ) );

  if( !ch->Is_Valid( ) )
    return;

  time = modify_delay( ch, time );

  if( ch->species != NULL )
    add_round( ch->species, time );

  if( ch->active.time == -1 ) 
    add_queue( &ch->active, time );
}
Esempio n. 19
0
int process_create(void(*f)(void), int n) {
    unsigned int sp_create;//Stack pointer (SP) for process

    /*Create queue_t and process_t (allocate memory)*/
    queue_t *elm = (queue_t *)malloc(sizeof(queue_t));
    elm->p = (process_t *)malloc(sizeof(process_t));

    //Initialize memory allocation for running the process
    _disable_interrupt();
    sp_create = process_init(f,n);
    _enable_interrupt();


    //If memory allocation failed
    if (sp_create == 0)return -1;
    else { //Memory Allocation Success. Set process's SP and Add elm to queue
        elm->p->sp = sp_create;
        add_queue(elm);
        return 0;
    }
}
Esempio n. 20
0
/* IF stuff */
void cmd_if(char *args)
{
    char cndtl[SMABUF];
    char rest[MAXSIZ];
    int parencnt = 0;
    char *p;
    char *q;

    p = skip_space(args);

    if ((*p != '(') || (strchr(args, ')') == (char *)NULL)) {
        msg("-- Usage: if (conditional expr) command");

        return;
    }

    for (q = p; *q; ++q) {
        if (*q == '(') {
            ++parencnt;
        } else if (*q == ')') {
            --parencnt;

            if (!parencnt) {
                break;
            }
        }
    }

    *q = '\0';
    strcpy(cndtl, p + 1);
    ++q;
    strcpy(rest, q);
    debug(2, "if: cndtl is %s", cndtl);
    debug(2, "if: rest is %s", rest);

    if (analyze_cndtl(cndtl)) {
        msg("IF HAS OCCURED");
        add_queue(rest, 0);
    }
}
Esempio n. 21
0
  void SetUp() override {
    connect(src0a.o, src_merge.a);
    connect(src0b.o, src_merge.b);
    connect(src_merge.o, fork.i);
    connect(src1.o, merge.b);
    connect(fork.a, q0.i);
    connect(fork.b, merge.a);
    connect(merge.o, q1.i);

    connect(q0.o, join.a);
    connect(q1.o, sw.i);
    connect(sw.a, join.b);
    connect(sw.b, s1.i);
    connect(join.o, s0.i);

    attachSwitchingFunction(&sw, {NAMED_ENUM("type", "rsp")});
    attachFunction(&join, [](const SymbolicPacket &a,
                             const SymbolicPacket &b) { return b; });

    attach(&src0a.o, {NAMED_ENUM("type", "rsp")});
    attach(&src0b.o, {NAMED_ENUM("type", "req")});
    attach(&src1.o, {NAMED_ENUM("type", "req")});

    components = {&s0,   &s1,        &q0,   &q1,    &src0a, &src0b,
                  &src1, &src_merge, &fork, &merge, &join,  &sw};

    auto state = XMASState{};
    state.add_queue(&q0, {});
    state.add_queue(&q1, {});
    reachable_states.insert({"initial state", std::move(state)});

    state = XMASState{};
    state.add_queue(&q0, {{{NAMED_ENUM("type", "rsp")}}});
    state.add_queue(&q1, {{{NAMED_ENUM("type", "rsp")}}});
    reachable_states.insert({"rsp in each queue", std::move(state)});

    state = XMASState{};
    state.add_queue(&q0, {{{NAMED_ENUM("type", "rsp")}}});
    state.add_queue(&q1, {});
    reachable_states.insert({"rsp in queue 0", std::move(state)});

    state = XMASState{};
    state.add_queue(
        &q0, {{{NAMED_ENUM("type", "rsp")}}, {{NAMED_ENUM("type", "rsp")}}});
    state.add_queue(&q1, {});
    unreachable_states.insert({"two rsp in queue 0", std::move(state)});
  }
Esempio n. 22
0
/* Selects process to run and returns its SP value */
unsigned int process_select (unsigned int cursp) {
    queue_t *temp;

    if (cursp == 0) {
        //No process was running
        if (current_process == NULL) { //first process
            if (queue_head != NULL) { //Queue is non-empty
                current_process = queue_head->p;
                return current_process->sp;
            }
            return 0;  //Queue is empty
        }
        //Current Process terminated
        if (queue_head->next != NULL) { //Select next process and update current process
            current_process = queue_head->next->p;
            queue_head = queue_head->next;
            return current_process->sp;
        }
        //No more processes to run
        queue_head = NULL;
        current_process = NULL;
        return 0;
    }
    else if (queue_head->next == NULL) {
        //Current Process is only process (and not terminated), update SP to cursp
        current_process->sp = cursp;
        return queue_head->p->sp;
    }
    else {
        //Current Process is not terminated but there is a ready process in queue
        //Update and Must switch to give other process a chance
        current_process->sp = cursp;
        temp = queue_head;
        remove_queue(); //Switch to next process (at head)
        add_queue(temp); //Add prev process back to queue since it did not terminate yet
        return queue_head->p->sp;
    }
}
Esempio n. 23
0
void Obj_Data :: To( content_array* where )
{
  event_data* event;
  room_data*   room;
  char_data*     ch;
  obj_data*     obj;
  int             i;

  if( array != NULL ) {
    roach( "Adding object somewhere which isn't nowhere." );
    roach( "-- Obj = %s", this );
    From( number );
    }

  if( ( room = Room( where->where ) ) != NULL ) {
    if( pIndexData->item_type == ITEM_CORPSE
      && value[0] > 0 ) {
      event = new event_data( execute_decay, this );
      add_queue( event, value[0] ); 
      }
    }

  if( ( ch = character( where->where ) ) != NULL
    && where == &ch->wearing ) {
    equip( ch, this );
    for( i = 0; i < ch->wearing; i++ ) {
      obj = (obj_data*) ch->wearing[i];
      if( obj->position > position 
        || ( obj->position == position
        && obj->layer > layer ) ) 
        break;
      }
    insert( *where, this, i );
    array = where; 
    }  

  Thing_Data :: To( where );
}
Esempio n. 24
0
void QContentHubServer::push_queue(msgpack::rpc::request &req, const std::string &name, const std::string &obj)
{
    queue_map_t &qmap = q_map.unsafe_ref();

    queue_map_it_t it = qmap.find(name);
    if (it == qmap.end()) {
        int ret = add_queue(name, DEFAULT_QUEUE_CAPACITY);
        if (ret == QCONTENTHUB_ERROR) {
            req.result(ret);
        } else {
            push_queue(req, name, obj);
        }
    } else {
        queue_t *q = it->second;
        pthread_mutex_lock(&q->lock);

        while ((int)q->str_q.size() > q->capacity) {
            struct timespec ts;
            clock_gettime(CLOCK_REALTIME, &ts);
            ts.tv_sec += 60;
            int rc = pthread_cond_timedwait(&q->not_full, &q->lock, &ts);
            if (rc == ETIMEDOUT) {
                pthread_mutex_unlock(&q->lock);
                req.result(QCONTENTHUB_STRAGAIN);
                return;
            } else if (rc != 0) {
                pthread_mutex_unlock(&q->lock);
                req.result(QCONTENTHUB_STRERROR);
                return;
            }
        }
        q->str_q.push(obj);
        pthread_cond_signal(&q->not_empty);
        pthread_mutex_unlock(&q->lock);
        req.result(QCONTENTHUB_OK);
    }
}
Esempio n. 25
0
void QContentHubServer::add_queue(msgpack::rpc::request &req, const std::string &name, int capacity)
{
    req.result(add_queue(name, capacity));
}
Esempio n. 26
0
void QContentHubServer::dispatch(msgpack::rpc::request req) {
    try {
        std::string method;
        req.method().convert(&method);

        if(method == "push") {
            msgpack::type::tuple<std::string, std::string> params;
            req.params().convert(&params);
            push_queue(req, params.get<0>(), params.get<1>());
        } else if(method == "pop") {
            msgpack::type::tuple<std::string> params;
            req.params().convert(&params);
            pop_queue(req, params.get<0>());
        } else if(method == "push_nowait") {
            msgpack::type::tuple<std::string, std::string> params;
            req.params().convert(&params);
            push_queue_nowait(req, params.get<0>(), params.get<1>());
        } else if(method == "pop_nowait") {
            msgpack::type::tuple<std::string> params;
            req.params().convert(&params);
            pop_queue_nowait(req, params.get<0>());
        } else if(method == "add") {
            msgpack::type::tuple<std::string, int> params;
            req.params().convert(&params);
            add_queue(req, params.get<0>(), params.get<1>());
        /*
        } else if(method == "del") {
            msgpack::type::tuple<std::string> params;
            req.params().convert(&params);
            del_queue(req, params.get<0>());
        } else if(method == "fdel") {
            msgpack::type::tuple<std::string> params;
            req.params().convert(&params);
            force_del_queue(req, params.get<0>());
        */
        } else if(method == "set_capacity") {
            msgpack::type::tuple<std::string, int> params;
            req.params().convert(&params);
            set_queue_capacity(req, params.get<0>(), params.get<1>());
        } else if(method == "start") {
            msgpack::type::tuple<std::string> params;
            req.params().convert(&params);
            start_queue(req, params.get<0>());
        } else if(method == "stop") {
            msgpack::type::tuple<std::string> params;
            req.params().convert(&params);
            stop_queue(req, params.get<0>());
        } else if(method == "clear") {
            msgpack::type::tuple<std::string> params;
            req.params().convert(&params);
            clear_queue(req, params.get<0>());
        } else if(method == "stats") {
            stats(req);
        } else if(method == "stat_queue") {
            msgpack::type::tuple<std::string> params;
            req.params().convert(&params);
            stat_queue(req, params.get<0>());
        } else {
            req.error(msgpack::rpc::NO_METHOD_ERROR);
        }
    } catch (msgpack::type_error& e) {
        req.error(msgpack::rpc::ARGUMENT_ERROR);
        return;

    } catch (std::exception& e) {
        req.error(std::string(e.what()));
        return;
    }
}
Esempio n. 27
0
void
thread_wakeup(thread_t *t)
{
	DPRINTF("t:%p\n", t);
	add_queue(t);
}
Esempio n. 28
0
//--------- Begin of function FirmHarbor::detect_build_menu ---------//
//
void FirmHarbor::detect_build_menu()
{
	int 	 	 unitId, x=INFO_X1+2, y=INFO_Y1, rc, quitFlag;
	UnitInfo* unitInfo;

	for(int b=0; b<added_count; ++b)
	{
		// ###### begin Gilbert 20/9 #########//
		unitId = button_ship[b].custom_para.value;
		// ###### end Gilbert 20/9 #########//
		unitInfo = unit_res[unitId];

		//------ detect pressing on the small queue count button -------//

		// ####### begin Gilbert 20/9 ########//
		rc = 0;
		if( (rc = button_queue_ship[b].detect(0,0,2)) != 0 )		// both button
		{
			quitFlag = 0;		// don't quit the menu right after pressing the button
		}

		//------ detect pressing on the big button -------//
		else if( (rc = button_ship[b].detect(0,0,2)) != 0 )
		{
			quitFlag = 1;		// quit the menu right after pressing the button
		}
		// ####### end Gilbert 20/9 ########//

		//------- process the action --------//

		if( rc > 0 )
		{
			if( rc==1 )		// left button
			{
				if( remote.is_enable() )
				{
					// packet structure : <firm recno> <unit Id>
					short *shortPtr = (short *)remote.new_send_queue_msg(MSG_F_HARBOR_BUILD_SHIP, 2*sizeof(short) );
					shortPtr[0] = firm_recno;
					shortPtr[1] = unitId;
				}
				else
					add_queue(unitId);
				// ##### begin Gilbert 25/9 ######//
				se_ctrl.immediate_sound("TURN_ON");
				// ##### end Gilbert 25/9 ######//
			}
			else 				// right button - remove queue
			{
				if( remote.is_enable() )
				{
					// packet structure : <firm recno> <unit Id>
					short *shortPtr = (short *)remote.new_send_queue_msg(MSG_F_HARBOR_BUILD_SHIP, 2*sizeof(short) );
					shortPtr[0] = firm_recno;
					shortPtr[1] = -unitId;
				}
				else
					remove_queue(unitId);

				// ##### begin Gilbert 25/9 ######//
				se_ctrl.immediate_sound("TURN_OFF");
				// ##### end Gilbert 25/9 ######//
			}

			if( quitFlag )
				info.disp();		// info.disp() will call put_info() which will switch mode back to the main menu mode
			else
			// ######## begin Gilbert 20/9 ########//
				// disp_queue_button(y+COUNT_BUTTON_OFFSET_Y, unitId, 1);
				info.update();
			// ######## end Gilbert 20/9 ########//

			return;
		}

		y += BUILD_BUTTON_HEIGHT;
	}

	//------ detect the cancel button --------//

	if( button_cancel.detect() || mouse.any_click(1) )		// press the cancel button or right click
	{
		harbor_menu_mode = HARBOR_MENU_MAIN;
		info.disp();
		// ###### begin Gilbert 26/9 #######//
		se_ctrl.immediate_sound("TURN_OFF");
		// ###### end Gilbert 26/9 #######//
	}
}
Esempio n. 29
0
int main(int argc, char** argv) {
    queue_unit use_list, wait_list, *use_p, *wait_p;
    if (init_queue(&use_list) == -1) {
        printf("use Queue Initialization failed");
        exit(EXIT_FAILURE);
    }
    if (init_queue(&wait_list) == -1) {
        printf("wait Queue Initialization failed");
        exit(EXIT_FAILURE);
    }
    int opt, cfp, len, sel, i, temp, port = PORT;
    int keepAlive = 1; // 开启keepalive属性
    int keepIdle = 5; // 如该连接在5秒内没有任何数据往来,则进行探测 
    int keepInterval = 5; // 探测时发包的时间间隔为5 秒
    int keepCount = 3; // 探测尝试的次数.如果第1次探测包就收到响应了,则后2次的不再发.
    struct sockaddr_in client_sockaddr, service_sockaddr;
    char buf[1024];
    while ((opt = getopt(argc, argv, "hp:")) != -1) {
        switch (opt) {
            case 'p':port = atoi(optarg);
                break;
            case 'h':
            default:
                printf("Welcome to use SocketLock For PHP\n"
                        "-h\t\t\t help \n"
                        "-p\t\t\t listen port\n");
        }
    }
    signal(SIGQUIT, sigroutine);
    signal(SIGKILL, sigroutine);
    sfp = socket(AF_INET, SOCK_STREAM, 0);
    setsockopt(sfp, SOL_SOCKET, SO_KEEPALIVE, (void *) &keepAlive, sizeof (keepAlive));
    setsockopt(sfp, SOL_TCP, TCP_KEEPIDLE, (void*) &keepIdle, sizeof (keepIdle));
    setsockopt(sfp, SOL_TCP, TCP_KEEPINTVL, (void *) &keepInterval, sizeof (keepInterval));
    setsockopt(sfp, SOL_TCP, TCP_KEEPCNT, (void *) &keepCount, sizeof (keepCount));
    service_sockaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    service_sockaddr.sin_family = AF_INET;
    service_sockaddr.sin_port = htons(port);
    if (-1 == bind(sfp, (struct sockaddr *) &service_sockaddr, sizeof (struct sockaddr))) {
        perror("bind error");
        exit(EXIT_FAILURE);
    }
    printf("bind success!\n");
    if (-1 == listen(sfp, MAX_NUM)) {
        perror("listen error");
        exit(EXIT_FAILURE);
    }
    printf("listen success!\n");
    socklen_t sl = sizeof (struct sockaddr_in);
    fd_set readset, bufset;
    FD_ZERO(&readset);
    FD_ZERO(&bufset);
    FD_SET(sfp, &readset);
    struct timeval tm;
    while (1) {
        tm.tv_sec = 5;
        tm.tv_usec = 0;
        memcpy(&bufset, &readset, sizeof (fd_set));
        sel = select(MAX_NUM + 1, &bufset, NULL, NULL, &tm);
        if (sel < 0) {
            perror("select error");
            exit(EXIT_FAILURE);
        }
        if (sel == 0) {
            printf("timeout!\n");
            printf("----use Queue!----\n");
            echo_queue(&use_list);
            printf("----wait Queue!----\n");
            echo_queue(&wait_list);
            continue;
        }
        if (FD_ISSET(sfp, &bufset)) {
            cfp = accept(sfp, (struct sockaddr *) &client_sockaddr, &sl);
            if (cfp == -1) {
                perror("accept error");
                exit(EXIT_FAILURE);
            }
            write(cfp, CONNECT_SIGNAL, strlen(CONNECT_SIGNAL));
            FD_SET(cfp, &readset);
            client_fd[cfp] = 1;
            printf("client success %d \n", cfp);
        }

        for (i = 0; i < MAX_NUM; i++) {
            if (FD_ISSET(i, &bufset)) {
                if (client_fd[i] == 1) {
                    len = read(i, buf, 1024);
                    if (len <= 0) {
                        client_fd[i] = 0;
                        FD_CLR(i, &readset);
                        close(i);
                        del_queue(&use_list, i, buf); //删除在用队列里的数据
                        printf("close: %d %s\n", i, buf);

                        use_p = find_in_queue(&wait_list, buf); //查找等待队列中是否有数据
                        if (use_p != NULL) {//如果有等待
                            temp = use_p->socket_num;
                            del_queue(&wait_list, temp, buf); //从等待队列中去除
                            printf("client: %d %s using\n", temp, buf);
                            add_queue(&use_list, temp, buf); //加入在用队列
                            write(cfp, CONNECT_SIGNAL, strlen(CONNECT_SIGNAL)); //发送通过信号
                        }
                    } else {
                        buf[len] = '\0';
                        use_p = find_in_queue(&use_list, buf);
                        if (use_p == NULL) {
                            printf("client: %d %s using\n", i, buf);
                            add_queue(&use_list, i, buf);
                            write(cfp, CONNECT_SIGNAL, strlen(CONNECT_SIGNAL)); //发送通过信号
                        } else {
                            add_queue(&wait_list, i, buf); //不许通过进入等待队列
                        }
                    }
                }

            }
        }
    }
    close(sfp);
    return (EXIT_SUCCESS);
}
Esempio n. 30
0
void FirmIncubator::detect_build_menu()
{
	int 	 	 unitId, rc, quitFlag;
	UnitInfo* unitInfo;

	for( int b = 0; b < added_count; ++b)
	{
		unitId = button_weapon[b].custom_para.value;
		unitInfo = unit_res[unitId];

		//------ detect pressing on the small queue count button -------//

		rc = 0;
		quitFlag = 0;

		if( (rc = button_queue_weapon[b].detect(0,0,2)) != 0 )		// both button
		{
			quitFlag = 0;		// don't quit the menu right after pressing the button
		}

		//------ detect pressing on the big button -------//

		else if( (rc = button_weapon[b].detect(0,0,2)) != 0 )
		{
			quitFlag = 1;		// quit the menu right after pressing the button
		}

		//------- process the action --------//

		if( rc > 0 )
		{
			if( rc==1 )		// left button
			{
				if( remote.is_enable() )
				{
					// packet structure : <firm recno> <unit Id>
					short *shortPtr = (short *)remote.new_send_queue_msg(MSG_F_WAR_BUILD_WEAPON, 2*sizeof(short) );
					shortPtr[0] = firm_recno;
					shortPtr[1] = unitId;
				}
				else
					add_queue(unitId);
				se_ctrl.immediate_sound("TURN_ON");
			}
			else 				// right button - remove queue
			{
				if( remote.is_enable() )
				{
					// packet structure : <firm recno> <unit Id>
					short *shortPtr = (short *)remote.new_send_queue_msg(MSG_F_WAR_CANCEL_WEAPON, 2*sizeof(short) );
					shortPtr[0] = firm_recno;
					shortPtr[1] = unitId;
				}
				else
					remove_queue(unitId);
				se_ctrl.immediate_sound("TURN_OFF");
			}

			if( quitFlag )
				war_menu_mode = WAR_MENU_MAIN;
			return;
		}

	}
	//------ detect the cancel button --------//

	if( button_cancel.detect() )
	{
		se_ctrl.immediate_sound("TURN_OFF");
		war_menu_mode = WAR_MENU_MAIN;
	}
}