void server(int port)
{
    linked_list_t *mapcycle_list = NULL;
    parse_mapcycle(&mapcycle_list);
    node_t *current_map = mapcycle_list->head;
    char port_game[100];
    char port_chat[100];
    char port_map[100];
    sprintf(port_game, "%d", port);
    sprintf(port_chat, "%d", port + 1);
    sprintf(port_map,  "%d", port + 2);
    signal(SIGTERM, sighandler);
    signal(SIGINT, sighandler);
    //node_t *current_map = mapcycle_list->head->next;
    while(server_running){
        printf("[SERVER] NEW GAME\n");
        player_list = malloc(sizeof(linked_list_t));
        observer_list = malloc(sizeof(linked_list_t));
        list_init(player_list);
        list_init(observer_list);
        int game_server_socket = prepare_server_UDP(port_game, AF_INET6);
        int chat_server_socket = prepare_server_TCP(port_chat, AF_INET6);
        int map_server_socket  = prepare_server_TCP(port_map , AF_INET6);

        current_map = current_map->next;
        if(current_map == mapcycle_list->tail){
            current_map = mapcycle_list->head->next;
        }
        game_server_init(current_map->data);

        fd_set descriptors_set;
        FD_ZERO(&descriptors_set);
        FD_SET(map_server_socket,  &descriptors_set);
        FD_SET(chat_server_socket, &descriptors_set);
        FD_SET(game_server_socket, &descriptors_set);


        int max_fd = map_server_socket > chat_server_socket ? map_server_socket : chat_server_socket;
        max_fd = max_fd > game_server_socket ? max_fd : game_server_socket;
        struct timeval timeout;
        memset(&timeout, 0, sizeof(struct timeval));
        timeout.tv_sec = 3;
        change_map = 0;
        while(!change_map){
            if(select(max_fd  + 1, &descriptors_set, NULL, NULL, &timeout) < 0) {
                continue;
            }

            timeout.tv_sec = 3;

            if (FD_ISSET(map_server_socket , &descriptors_set)){
                map_server(map_server_socket, current_map_id);
            }

            if (FD_ISSET(chat_server_socket , &descriptors_set)){
                chat_server(chat_server_socket);
            }

            if (FD_ISSET(game_server_socket , &descriptors_set)){
                game_server(game_server_socket);
            }

            for (node_t *i = player_list->head->next; i != player_list->tail; i = i->next){
                player_info_t *player_info = (player_info_t*)i->data;
                if (FD_ISSET(player_info->chat_descriptor , &descriptors_set)){
                    char buffer[129];
                    memset(buffer, 0, 129);
                    int full_recv = 0;
                    int bytes_recv = chat_recv(player_info->chat_descriptor, buffer, &full_recv);
                    if(bytes_recv == 0){
                        //HANDLE DISCONNECT
                        int player_id = player_info->playerID;

                        close(player_info->chat_descriptor);
                        node_t *previous = i->previous;
                        list_remove_node(i, player_list);
                        i = previous;

                        if (player_id == 255){
                            continue;
                        }

                        char buffer[129];
                        sprintf(buffer, "Player %"SCNu8" disconnected", player_id);
                        printf("[CHAT SERVER] %s\n", buffer);
                        broadcast_disconnection_ack(game_server_socket, player_id, player_list);
                        chat_forward_msg(0, buffer, player_list);
                    }else if (bytes_recv < 0){
                        printf("[CHAT SERVER] Error receiving from %"SCNu8"%s\n", player_info->playerID, strerror(errno));
                    }else if (full_recv){
                        if (buffer[2] == '*'){
                            change_map = 1;
                        }
                        if (player_info->playerID == 255){
                            continue;
                        }
                        chat_forward_msg(player_info->playerID, &buffer[2], player_list);
                        gettimeofday(&player_info->last_action, NULL);
                    }
                }
            }

            remove_idle_players(game_server_socket);
            respawn_death_players(game_server_socket);

            FD_ZERO(&descriptors_set);
            FD_SET(map_server_socket,  &descriptors_set);
            FD_SET(chat_server_socket, &descriptors_set);
            FD_SET(game_server_socket, &descriptors_set);
            max_fd = map_server_socket > chat_server_socket ? map_server_socket : chat_server_socket;
            max_fd = max_fd > game_server_socket ? max_fd : game_server_socket;
            for (node_t *i = player_list->head->next; i != player_list->tail; i = i->next){
                player_info_t *player_info = (player_info_t*)i->data;
                FD_SET(player_info->chat_descriptor, &descriptors_set);
                if (player_info->chat_descriptor > max_fd){
                    max_fd = player_info->chat_descriptor;
                }
            }
            if (change_map){
                sleep(5);
                broadcast_map_change(game_server_socket, player_list);
            }
        }
        change_map = 0;
        for(node_t *i = player_list->head->next; i != player_list->tail; i = i->next){
            player_info_t *player_info = (player_info_t*)i->data;
            close(player_info->chat_descriptor);
        }

        list_delete(player_list);
        free(player_list);
        list_delete(observer_list);
        game_server_shutdown();
        free(observer_list);
        close(map_server_socket);
        close(chat_server_socket);
        close(game_server_socket);
    }
    delete_mapcycle_list(&mapcycle_list);
}
Example #2
0
int main()
{
    town tw, tw1, tw2, peeked;
    list_status_t *popStatus, *peekStatus;
    list_status_t putStatus;
    strcmp(tw.name, "city 0");
    strcmp(tw1.name, "city 1");
    strcmp(tw2.name, "city 2");
    tw.place.x = 5;
    tw.place.y = 5;
    tw1.place.x = 10;
    tw1.place.y = 10;
    tw2.place.x = 11;
    tw2.place.y = 11;
    list_t *ls;
    ls = list_new();
    putStatus = list_put(ls, tw, 5);
    if(putStatus == LIST_FULL)
        printf("List is full");
    if (putStatus == ERROR)
    {
        printf("Invalid index");
        return EXIT_FAILURE;
    }
    putStatus = list_put(ls, tw1, 0);
    if(putStatus == LIST_FULL)
        printf("List is full");
    if (putStatus == ERROR)
    {
        printf("Invalid index");
        return EXIT_FAILURE;
    }
    putStatus = list_put(ls, tw1, 4);
    if(putStatus == LIST_FULL)
        printf("List is full");
    if (putStatus == ERROR)
    {
        printf("Invalid index");
        return EXIT_FAILURE;
    }
    putStatus = list_put(ls, tw2, 4);
    if(putStatus == LIST_FULL)
        printf("List is full");
    if (putStatus == ERROR)
    {
        printf("Invalid index");
        return EXIT_FAILURE;
    }
    list_pop(ls, 2, popStatus);
    if (*popStatus == LIST_EMPTY)
    {
        printf("List is empty");
    }
    if(*popStatus == ERROR)
    {
        printf("Invalid index");
        return EXIT_FAILURE;
    }
    list_print(ls);
    peeked = list_peek(ls, 1, peekStatus);
    if(*peekStatus == LIST_EMPTY)
        printf("List is empty");
    if (*peekStatus == ERROR)
    {
        printf("Invalid index");
        return EXIT_FAILURE;
    }
    printf("\nPeeked %d %d", peeked.place.x, peeked.place.y);
    int c1 = 1, c2 = 2;
    double dis = distacnce(ls, c1, c2);
    if(!dis)
        printf("\nInvalid index");
    else
    printf("\nDistance between %d and %d is %f", c1, c2, dis);
    printf("\nCount %d", (list_getCount(ls)+1));
    list_delete(ls);
    return 0;
}
/**
 * @brief Creates threads to handle messages received from Clients.
 *
 * @param[in] pdwClientID Connection ID used to reference the Client.
 *
 * @return Error code.
 * @retval SCARD_S_SUCCESS Success.
 * @retval SCARD_F_INTERNAL_ERROR Exceded the maximum number of simultaneous Application Contexts.
 * @retval SCARD_E_NO_MEMORY Error creating the Context Thread.
 */
LONG CreateContextThread(uint32_t *pdwClientID)
{
	int rv;
	int lrv;
	int listSize;
	SCONTEXT * newContext = NULL;
	LONG retval = SCARD_E_NO_MEMORY;

	(void)pthread_mutex_lock(&contextsList_lock);

	listSize = list_size(&contextsList);
	if (listSize >= contextMaxThreadCounter)
	{
		Log2(PCSC_LOG_CRITICAL, "Too many context running: %d", listSize);
		goto out;
	}

	/* Create the context for this thread. */
	newContext = malloc(sizeof(*newContext));
	if (NULL == newContext)
	{
		Log1(PCSC_LOG_CRITICAL, "Could not allocate new context");
		goto out;
	}
	memset(newContext, 0, sizeof(*newContext));

	newContext->dwClientID = *pdwClientID;

	/* Initialise the list of card contexts */
	lrv = list_init(&newContext->cardsList);
	if (lrv < 0)
	{
		Log2(PCSC_LOG_CRITICAL, "list_init failed with return value: %d", lrv);
		goto out;
	}

	/* request to store copies, and provide the metric function */
	list_attributes_copy(&newContext->cardsList, list_meter_int32_t, 1);

	/* Adding a comparator
	 * The stored type is SCARDHANDLE (long) but has only 32 bits
	 * usefull even on a 64-bit CPU since the API between pcscd and
	 * libpcscliter uses "int32_t hCard;"
	 */
	lrv = list_attributes_comparator(&newContext->cardsList,
		list_comparator_int32_t);
	if (lrv != 0)
	{
		Log2(PCSC_LOG_CRITICAL,
			"list_attributes_comparator failed with return value: %d", lrv);
		list_destroy(&newContext->cardsList);
		goto out;
	}

	(void)pthread_mutex_init(&newContext->cardsList_lock, NULL);

	lrv = list_append(&contextsList, newContext);
	if (lrv < 0)
	{
		Log2(PCSC_LOG_CRITICAL, "list_append failed with return value: %d",
			lrv);
		list_destroy(&newContext->cardsList);
		goto out;
	}

	rv = ThreadCreate(&newContext->pthThread, THREAD_ATTR_DETACHED,
		(PCSCLITE_THREAD_FUNCTION( )) ContextThread, (LPVOID) newContext);
	if (rv)
	{
		int lrv2;

		Log2(PCSC_LOG_CRITICAL, "ThreadCreate failed: %s", strerror(rv));
		lrv2 = list_delete(&contextsList, newContext);
		if (lrv2 < 0)
			Log2(PCSC_LOG_CRITICAL, "list_delete failed with error %d", lrv2);
		list_destroy(&newContext->cardsList);
		goto out;
	}

	/* disable any suicide alarm */
	if (AutoExit)
		alarm(0);

	retval = SCARD_S_SUCCESS;

out:
	(void)pthread_mutex_unlock(&contextsList_lock);

	if (retval != SCARD_S_SUCCESS)
	{
		if (newContext)
			free(newContext);
		(void)close(*pdwClientID);
	}

	return retval;
}
Example #4
0
lnode_t *list_del_last(list_t *list)
{
    return list_delete(list, list->nilnode.prev);
}
Example #5
0
void
ContQuerySchedulerMain(int argc, char *argv[])
{
	sigjmp_buf local_sigjmp_buf;
	List *dbs = NIL;

	/* we are a postmaster subprocess now */
	IsUnderPostmaster = true;
	am_cont_scheduler = true;

	/* reset MyProcPid */
	MyProcPid = getpid();
	MyPMChildSlot = AssignPostmasterChildSlot();

	/* record Start Time for logging */
	MyStartTime = time(NULL);

	/* Identify myself via ps */
	init_ps_display("continuous query scheduler process", "", "", "");

	ereport(LOG, (errmsg("continuous query scheduler started")));

	if (PostAuthDelay)
		pg_usleep(PostAuthDelay * 1000000L);

	SetProcessingMode(InitProcessing);

	/*
	 * If possible, make this process a group leader, so that the postmaster
	 * can signal any child processes too. This is only for consistency sake, we
	 * never fork the scheduler process. Instead dynamic bgworkers are used.
	 */
#ifdef HAVE_SETSID
	if (setsid() < 0)
		elog(FATAL, "setsid() failed: %m");
#endif

	/*
	 * Set up signal handlers.  We operate on databases much like a regular
	 * backend, so we use the same signal handling.  See equivalent code in
	 * tcop/postgres.c.
	 */
	pqsignal(SIGHUP, sighup_handler);
	pqsignal(SIGINT, sigint_handler);
	pqsignal(SIGTERM, sigterm_handler);

	pqsignal(SIGQUIT, quickdie);
	InitializeTimeouts(); /* establishes SIGALRM handler */

	pqsignal(SIGPIPE, SIG_IGN);
	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
	pqsignal(SIGUSR2, sigusr2_handler);
	pqsignal(SIGFPE, FloatExceptionHandler);
	pqsignal(SIGCHLD, SIG_DFL);

#define BACKTRACE_SEGFAULTS
#ifdef BACKTRACE_SEGFAULTS
	pqsignal(SIGSEGV, debug_segfault);
#endif

	/* Early initialization */
	BaseInit();

	/*
	 * Create a per-backend PGPROC struct in shared memory, except in the
	 * EXEC_BACKEND case where this was done in SubPostmasterMain. We must do
	 * this before we can use LWLocks (and in the EXEC_BACKEND case we already
	 * had to do some stuff with LWLocks).
	 */
#ifndef EXEC_BACKEND
	InitProcess();
#endif

	InitPostgres(NULL, InvalidOid, NULL, NULL);

	SetProcessingMode(NormalProcessing);

	/*
	 * Create a memory context that we will do all our work in.  We do this so
	 * that we can reset the context during error recovery and thereby avoid
	 * possible memory leaks.
	 */
	ContQuerySchedulerMemCxt = AllocSetContextCreate(TopMemoryContext,
			"ContQuerySchedulerCtx",
			ALLOCSET_DEFAULT_MINSIZE,
			ALLOCSET_DEFAULT_INITSIZE,
			ALLOCSET_DEFAULT_MAXSIZE);
	MemoryContextSwitchTo(ContQuerySchedulerMemCxt);

	/*
	 * If an exception is encountered, processing resumes here.
	 *
	 * This code is a stripped down version of PostgresMain error recovery.
	 */
	if (sigsetjmp(local_sigjmp_buf, 1) != 0)
	{
		/* since not using PG_TRY, must reset error stack by hand */
		error_context_stack = NULL;

		/* Prevents interrupts while cleaning up */
		HOLD_INTERRUPTS();

		/* Forget any pending QueryCancel or timeout request */
		disable_all_timeouts(false);
		QueryCancelPending = false; /* second to avoid race condition */

		/* Report the error to the server log */
		EmitErrorReport();

		/* Abort the current transaction in order to recover */
		AbortCurrentTransaction();

		/*
		 * Now return to normal top-level context and clear ErrorContext for
		 * next time.
		 */
		MemoryContextSwitchTo(ContQuerySchedulerMemCxt);
		FlushErrorState();

		/* Flush any leaked data in the top-level context */
		MemoryContextResetAndDeleteChildren(ContQuerySchedulerMemCxt);

		/* Now we can allow interrupts again */
		RESUME_INTERRUPTS();

		/*
		 * Sleep at least 1 second after any error.  We don't want to be
		 * filling the error logs as fast as we can.
		 */
		pg_usleep(1000000L);
	}
	/* We can now handle ereport(ERROR) */
	PG_exception_stack = &local_sigjmp_buf;

	/* must unblock signals before calling rebuild_database_list */
	PG_SETMASK(&UnBlockSig);

	ContQuerySchedulerShmem->scheduler_pid = MyProcPid;

	dbs = get_database_list();

	/* Loop forever */
	for (;;)
	{
		ListCell *lc;
		int rc;

		foreach(lc, dbs)
		{
			DatabaseEntry *db_entry = lfirst(lc);
			bool found;
			ContQueryProcGroup *grp = hash_search(ContQuerySchedulerShmem->proc_table, &db_entry->oid, HASH_ENTER, &found);

			/* If we don't have an entry for this dboid, initialize a new one and fire off bg procs */
			if (!found)
			{
				grp->db_oid = db_entry->oid;
				namestrcpy(&grp->db_name, NameStr(db_entry->name));

				start_group(grp);
			}
		}

		/* Allow sinval catchup interrupts while sleeping */
		EnableCatchupInterrupt();

		/*
		 * Wait until naptime expires or we get some type of signal (all the
		 * signal handlers will wake us by calling SetLatch).
		 */
		rc = WaitLatch(&MyProc->procLatch, WL_LATCH_SET | WL_POSTMASTER_DEATH, 0);

		ResetLatch(&MyProc->procLatch);

		DisableCatchupInterrupt();

		/*
		 * Emergency bailout if postmaster has died.  This is to avoid the
		 * necessity for manual cleanup of all postmaster children.
		 */
		if (rc & WL_POSTMASTER_DEATH)
			proc_exit(1);

		/* the normal shutdown case */
		if (got_SIGTERM)
			break;

		/* update config? */
		if (got_SIGHUP)
		{
			got_SIGHUP = false;
			ProcessConfigFile(PGC_SIGHUP);

			/* update tuning parameters, so that they can be read downstream by background processes */
			update_tuning_params();
		}

		/* terminate a proc group? */
		if (got_SIGUSR2)
		{
			HASH_SEQ_STATUS status;
			ContQueryProcGroup *grp;

			got_SIGUSR2 = false;

			hash_seq_init(&status, ContQuerySchedulerShmem->proc_table);
			while ((grp = (ContQueryProcGroup *) hash_seq_search(&status)) != NULL)
			{
				ListCell *lc;

				if (!grp->terminate)
					continue;

				foreach(lc, dbs)
				{
					DatabaseEntry *entry = lfirst(lc);
					if (entry->oid == grp->db_oid)
					{
						dbs = list_delete(dbs, entry);
						break;
					}
				}

				terminate_group(grp);
			}
		}
Example #6
0
static void
ospf6_vertex_delete (struct ospf6_vertex *v)
{
  list_delete (v->child_list);
  XFREE (MTYPE_OSPF6_VERTEX, v);
}
Example #7
0
// using pstapriv->sta_hash_lock to protect
u32	free_stainfo(_adapter *padapter , struct sta_info *psta)
{
    int i;
    _irqL irqL0;
    _queue *pfree_sta_queue;
    struct recv_reorder_ctrl *preorder_ctrl;
    struct	sta_xmit_priv	*pstaxmitpriv;
    struct	xmit_priv	*pxmitpriv= &padapter->xmitpriv;
    struct	sta_priv *pstapriv = &padapter->stapriv;


    _func_enter_;

    if (psta == NULL)
        goto exit;

    pfree_sta_queue = &pstapriv->free_sta_queue;


    pstaxmitpriv = &psta->sta_xmitpriv;

    //list_delete(&psta->sleep_list);

    //list_delete(&psta->wakeup_list);

    _enter_critical_bh(&(pxmitpriv->vo_pending.lock), &irqL0);

    free_xmitframe_queue( pxmitpriv, &pstaxmitpriv->vo_q.sta_pending);

    list_delete(&(pstaxmitpriv->vo_q.tx_pending));

    _exit_critical_bh(&(pxmitpriv->vo_pending.lock), &irqL0);


    _enter_critical_bh(&(pxmitpriv->vi_pending.lock), &irqL0);

    free_xmitframe_queue( pxmitpriv, &pstaxmitpriv->vi_q.sta_pending);

    list_delete(&(pstaxmitpriv->vi_q.tx_pending));

    _exit_critical_bh(&(pxmitpriv->vi_pending.lock), &irqL0);


    _enter_critical_bh(&(pxmitpriv->bk_pending.lock), &irqL0);

    free_xmitframe_queue( pxmitpriv, &pstaxmitpriv->bk_q.sta_pending);

    list_delete(&(pstaxmitpriv->bk_q.tx_pending));

    _exit_critical_bh(&(pxmitpriv->bk_pending.lock), &irqL0);

    _enter_critical_bh(&(pxmitpriv->be_pending.lock), &irqL0);

    free_xmitframe_queue( pxmitpriv, &pstaxmitpriv->be_q.sta_pending);

    list_delete(&(pstaxmitpriv->be_q.tx_pending));

    _exit_critical_bh(&(pxmitpriv->be_pending.lock), &irqL0);


    list_delete(&psta->hash_list);
    RT_TRACE(_module_rtl871x_sta_mgt_c_,_drv_err_,("\n free number_%d stainfo  with hwaddr = 0x%.2x 0x%.2x 0x%.2x 0x%.2x 0x%.2x 0x%.2x  \n",pstapriv->asoc_sta_count , psta->hwaddr[0], psta->hwaddr[1], psta->hwaddr[2],psta->hwaddr[3],psta->hwaddr[4],psta->hwaddr[5]));
    pstapriv->asoc_sta_count --;


    // re-init sta_info; 20061114
    _init_sta_xmit_priv(&psta->sta_xmitpriv);
    _init_sta_recv_priv(&psta->sta_recvpriv);


    //for A-MPDU Rx reordering buffer control, cancel reordering_ctrl_timer
    for(i=0; i < 16 ; i++)
    {
        preorder_ctrl = &psta->recvreorder_ctrl[i];

        _cancel_timer_ex(&preorder_ctrl->reordering_ctrl_timer);
    }

    _spinlock(&(pfree_sta_queue->lock));
    // insert into free_sta_queue; 20061114
    list_insert_tail(&psta->list, get_list_head(pfree_sta_queue));
    _spinunlock(&(pfree_sta_queue->lock));


exit:

    _func_exit_;

    return _SUCCESS;

}
Example #8
0
int mi_lock_database(MI_INFO *info, int lock_type)
{
  int error;
  uint count;
  MYISAM_SHARE *share=info->s;
  DBUG_ENTER("mi_lock_database");
  DBUG_PRINT("enter",("lock_type: %d  old lock %d  r_locks: %u  w_locks: %u "
                      "global_changed:  %d  open_count: %u  name: '%s'",
                      lock_type, info->lock_type, share->r_locks,
                      share->w_locks,
                      share->global_changed, share->state.open_count,
                      share->index_file_name));
  if (share->options & HA_OPTION_READ_ONLY_DATA ||
      info->lock_type == lock_type)
    DBUG_RETURN(0);
  if (lock_type == F_EXTRA_LCK)                 /* Used by TMP tables */
  {
    ++share->w_locks;
    ++share->tot_locks;
    info->lock_type= lock_type;
    info->s->in_use= list_add(info->s->in_use, &info->in_use);
    DBUG_RETURN(0);
  }

  error= 0;
  mysql_mutex_lock(&share->intern_lock);
  if (share->kfile >= 0)		/* May only be false on windows */
  {
    switch (lock_type) {
    case F_UNLCK:
      ftparser_call_deinitializer(info);
      if (info->lock_type == F_RDLCK)
	count= --share->r_locks;
      else
	count= --share->w_locks;
      --share->tot_locks;
      if (info->lock_type == F_WRLCK && !share->w_locks &&
	  !share->delay_key_write && flush_key_blocks(share->key_cache,
						      share->kfile,FLUSH_KEEP))
      {
	error=my_errno;
        mi_print_error(info->s, HA_ERR_CRASHED);
	mi_mark_crashed(info);		/* Mark that table must be checked */
      }
      if (info->opt_flag & (READ_CACHE_USED | WRITE_CACHE_USED))
      {
	if (end_io_cache(&info->rec_cache))
	{
	  error=my_errno;
          mi_print_error(info->s, HA_ERR_CRASHED);
	  mi_mark_crashed(info);
	}
      }
      if (!count)
      {
	DBUG_PRINT("info",("changed: %u  w_locks: %u",
			   (uint) share->changed, share->w_locks));
	if (share->changed && !share->w_locks)
	{
#ifdef HAVE_MMAP
    if ((info->s->mmaped_length != info->s->state.state.data_file_length) &&
        (info->s->nonmmaped_inserts > MAX_NONMAPPED_INSERTS))
    {
      if (info->s->concurrent_insert)
        mysql_rwlock_wrlock(&info->s->mmap_lock);
      mi_remap_file(info, info->s->state.state.data_file_length);
      info->s->nonmmaped_inserts= 0;
      if (info->s->concurrent_insert)
        mysql_rwlock_unlock(&info->s->mmap_lock);
    }
#endif
	  share->state.process= share->last_process=share->this_process;
	  share->state.unique=   info->last_unique=  info->this_unique;
	  share->state.update_count= info->last_loop= ++info->this_loop;
          if (mi_state_info_write(share->kfile, &share->state, 1))
	    error=my_errno;
	  share->changed=0;
	  if (myisam_flush)
	  {
            if (mysql_file_sync(share->kfile, MYF(0)))
	      error= my_errno;
            if (mysql_file_sync(info->dfile, MYF(0)))
	      error= my_errno;
	  }
	  else
	    share->not_flushed=1;
	  if (error)
          {
            mi_print_error(info->s, HA_ERR_CRASHED);
	    mi_mark_crashed(info);
          }
	}
	if (info->lock_type != F_EXTRA_LCK)
	{
	  if (share->r_locks)
	  {					/* Only read locks left */
	    if (my_lock(share->kfile,F_RDLCK,0L,F_TO_EOF,
			MYF(MY_WME | MY_SEEK_NOT_DONE)) && !error)
	      error=my_errno;
	  }
	  else if (!share->w_locks)
	  {					/* No more locks */
	    if (my_lock(share->kfile,F_UNLCK,0L,F_TO_EOF,
			MYF(MY_WME | MY_SEEK_NOT_DONE)) && !error)
	      error=my_errno;
	  }
	}
      }
      info->opt_flag&= ~(READ_CACHE_USED | WRITE_CACHE_USED);
      info->lock_type= F_UNLCK;
      info->s->in_use= list_delete(info->s->in_use, &info->in_use);
      break;
    case F_RDLCK:
      if (info->lock_type == F_WRLCK)
      {
        /*
          Change RW to READONLY

          mysqld does not turn write locks to read locks,
          so we're never here in mysqld.
        */
	if (share->w_locks == 1)
	{
          if (my_lock(share->kfile,lock_type,0L,F_TO_EOF,
		      MYF(MY_SEEK_NOT_DONE)))
	  {
	    error=my_errno;
	    break;
	  }
	}
	share->w_locks--;
	share->r_locks++;
	info->lock_type=lock_type;
	break;
      }
      if (!share->r_locks && !share->w_locks)
      {
	if (my_lock(share->kfile,lock_type,0L,F_TO_EOF,
		    info->lock_wait | MY_SEEK_NOT_DONE))
	{
	  error=my_errno;
	  break;
	}
	if (mi_state_info_read_dsk(share->kfile, &share->state, 1))
	{
	  error=my_errno;
	  (void) my_lock(share->kfile,F_UNLCK,0L,F_TO_EOF,MYF(MY_SEEK_NOT_DONE));
	  my_errno=error;
	  break;
	}
      }
      (void) _mi_test_if_changed(info);
      share->r_locks++;
      share->tot_locks++;
      info->lock_type=lock_type;
      info->s->in_use= list_add(info->s->in_use, &info->in_use);
      break;
    case F_WRLCK:
      if (info->lock_type == F_RDLCK)
      {						/* Change READONLY to RW */
	if (share->r_locks == 1)
	{
	  if (my_lock(share->kfile,lock_type,0L,F_TO_EOF,
		      MYF(info->lock_wait | MY_SEEK_NOT_DONE)))
	  {
	    error=my_errno;
	    break;
	  }
	  share->r_locks--;
	  share->w_locks++;
	  info->lock_type=lock_type;
	  break;
	}
      }
      if (!(share->options & HA_OPTION_READ_ONLY_DATA))
      {
	if (!share->w_locks)
	{
	  if (my_lock(share->kfile,lock_type,0L,F_TO_EOF,
		      info->lock_wait | MY_SEEK_NOT_DONE))
	  {
	    error=my_errno;
	    break;
	  }
	  if (!share->r_locks)
	  {
	    if (mi_state_info_read_dsk(share->kfile, &share->state, 1))
	    {
	      error=my_errno;
	      (void) my_lock(share->kfile,F_UNLCK,0L,F_TO_EOF,
			   info->lock_wait | MY_SEEK_NOT_DONE);
	      my_errno=error;
	      break;
	    }
	  }
	}
      }
      (void) _mi_test_if_changed(info);
        
      info->lock_type=lock_type;
      info->invalidator=info->s->invalidator;
      share->w_locks++;
      share->tot_locks++;
      info->s->in_use= list_add(info->s->in_use, &info->in_use);
      break;
    default:
      break;				/* Impossible */
    }
  }
#ifdef _WIN32
  else
  {
    /*
       Check for bad file descriptors if this table is part
       of a merge union. Failing to capture this may cause
       a crash on windows if the table is renamed and 
       later on referenced by the merge table.
     */
    if( info->owned_by_merge && (info->s)->kfile < 0 )
    {
      error = HA_ERR_NO_SUCH_TABLE;
    }
  }
#endif
  mysql_mutex_unlock(&share->intern_lock);
  DBUG_RETURN(error);
} /* mi_lock_database */
Example #9
0
int main(int argc, char **argv) {

	  //get Input
	  int sequential = 1;
	  int count = 0;
	  printf("Prompt: ");
	  fflush(stdout);
	  char line[1024];

	  for(;fgets(line, 1024, stdin) != NULL; printf("Prompt: ")) {
		    for (int i =0; i<1024; i++){
			      if (line[i]=='\n'){
			        line[i]='\0';
			      }
		    }

		    //tokenify the line. Returns separate commands.
		    char ** tokens = tokenify(line);
		    int exit_terminal = 0;
		    int mode_switch = 0;
		    pid_t pid;

		    for (int i=0; tokens[i]!=NULL; i++){
	          char ** results = parse_command(tokens[i]);
	          int overhead_command = overhead(results, sequential);
	          //if (overhead_command==0) do nothing.
            if (overhead_command > 0) {
                // free
            }
	          if (overhead_command==1){
	              //exit command issued
	              exit_terminal = 1;
                free(results);
	              continue;
	          }
	          if (overhead_command==2){
	              //switch to sequential mode
	              mode_switch = 1;
	              continue;
	          }
	          if (overhead_command==3){
	              //switch to parallel
	              mode_switch = 2;
	              continue;
	          }
	          if (overhead_command==4){
	              //already printed what mode we are in
	              continue;
	          }

	          pid = fork();

	          if (pid==0){
								FILE *fp;
								fp = fopen("shell-config", "r");
								char holder[20];
								// initialize linked list to store paths
								struct node *head = NULL;
								while (fscanf(fp, "%s/n", holder) != EOF) {
								    list_insert(holder, &head);
								}
                fclose(fp);

								struct node *iterator = head;
								struct stat statresult;
								int rv = stat(results[0], &statresult);

                //printf("%i\n", rv);

                // this loop checks to see if there are any path folders that may contain the command
								if (rv < 0){
			              //printf("RV not negative\n");
                    //printf("%s\n", iterator -> name);

									  while (iterator != NULL){

                        char* name = strdup(iterator -> name);

                        rv = stat(iterator->name, &statresult);

                        if (rv < 0){
                            // not found
                            continue;
                        } else {
                            results[0] = iterator -> name;
                        }

                        rv = stat(iterator->name, &statresult);
                        iterator = iterator -> next;
									  }

								} 
                list_delete(head);
                //printf("results[0]: %s\n", results[0]);
	              if (execv(results[0],results)<0){
	                  printf("Process entered is wrong.\n");
	                  exit(0);
	              }
	          }
	          if (sequential) {
	              wait(&pid);
	          }
		    }

		    if (sequential == 0){
		        wait(&pid);
		    }

		    if (exit_terminal==1){
            free(tokens);
	          return 0;
		    }
		    if (mode_switch==1){
		        sequential = 1; //switch to sequential
		    }
		    if (mode_switch==2){
		        sequential = 0; //switch to parallel
		    }

		    count ++;
	  }
	  return 0;
}
Example #10
0
//struct	sta_info *alloc_stainfo(_queue *pfree_sta_queue, unsigned char *hwaddr)
struct	sta_info *alloc_stainfo(struct	sta_priv *pstapriv, u8 *hwaddr)
{
    uint tmp_aid;
    s32	index;
    _list	*phash_list;
    struct sta_info	*psta;
    _queue *pfree_sta_queue;
    struct recv_reorder_ctrl *preorder_ctrl;
    int i = 0;
    u16  wRxSeqInitialValue = 0xffff;

    _func_enter_;

    pfree_sta_queue = &pstapriv->free_sta_queue;

    _spinlock(&(pfree_sta_queue->lock));

    if (_queue_empty(pfree_sta_queue) == _TRUE)
    {
        psta = NULL;
    }
    else
    {
        psta = LIST_CONTAINOR(get_next(&pfree_sta_queue->queue), struct sta_info, list);

        list_delete(&(psta->list));

        tmp_aid = psta->aid;

        _init_stainfo(psta);

        _memcpy(psta->hwaddr, hwaddr, ETH_ALEN);

        index = wifi_mac_hash(hwaddr);

        RT_TRACE(_module_rtl871x_sta_mgt_c_,_drv_info_,("alloc_stainfo: index  = %x", index));

        if(index >= NUM_STA) {
            RT_TRACE(_module_rtl871x_sta_mgt_c_,_drv_err_,("ERROR=> alloc_stainfo: index >= NUM_STA"));
            psta= NULL;
            goto exit;
        }
        phash_list = &(pstapriv->sta_hash[index]);

        _spinlock(&(pstapriv->sta_hash_lock));

        list_insert_tail(&psta->hash_list, phash_list);

        pstapriv->asoc_sta_count ++ ;

        _spinunlock(&(pstapriv->sta_hash_lock));

// Commented by Albert 2009/08/13
// For the SMC router, the sequence number of first packet of WPS handshake will be 0.
// In this case, this packet will be dropped by recv_decache function if we use the 0x00 as the default value for tid_rxseq variable.
// So, we initialize the tid_rxseq variable as the 0xffff.

        for( i = 0; i < 16; i++ )
        {
            _memcpy( &psta->sta_recvpriv.rxcache.tid_rxseq[ i ], &wRxSeqInitialValue, 2 );
        }

        RT_TRACE(_module_rtl871x_sta_mgt_c_,_drv_info_,("alloc number_%d stainfo  with hwaddr = %x %x %x %x %x %x  \n",
                 pstapriv->asoc_sta_count , hwaddr[0], hwaddr[1], hwaddr[2],hwaddr[3],hwaddr[4],hwaddr[5]));



        //for A-MPDU Rx reordering buffer control
        for(i=0; i < 16 ; i++)
        {
            preorder_ctrl = &psta->recvreorder_ctrl[i];

            preorder_ctrl->padapter = pstapriv->padapter;

            preorder_ctrl->enable = _FALSE;

            preorder_ctrl->indicate_seq = 0xffff;
            preorder_ctrl->wend_b= 0xffff;
            //preorder_ctrl->wsize_b = (NR_RECVBUFF-2);
            preorder_ctrl->wsize_b = 64;//64;

            _init_queue(&preorder_ctrl->pending_recvframe_queue);

            init_recv_timer(preorder_ctrl);
        }

    }

exit:

    _spinunlock(&(pfree_sta_queue->lock));

    _func_exit_;

    return psta;


}
Example #11
0
static void TimerCalcNextRun(Timer *timer, lnode_t *node) {
	struct tm *newtime;
	Timer *CurTimer, *NextTimer;
	lnode_t *CurNode, *NextNode;

	newtime = localtime(&timer->lastrun);
	switch(timer->type) {
		case TIMER_TYPE_DAILY:
			newtime->tm_hour = 0;
			newtime->tm_min = 0;
			newtime->tm_sec = 0;
			newtime->tm_mday += 1;
			break;
		case TIMER_TYPE_WEEKLY:
			/* weekly and monthly timers can run at any time */
			newtime->tm_mday += 7;
			break;
		case TIMER_TYPE_MONTHLY:
			newtime->tm_mon += 1;
			break;
		case TIMER_TYPE_INTERVAL:
			newtime->tm_sec += timer->interval;
			break;
		case TIMER_TYPE_COUNTDOWN:
#if 0
					if( me.now - timer->lastrun < timer->interval )
					{
						timer->interval -= ( me.now - timer->lastrun );
						timer->lastrun = me.now;
 						continue;
					}
#endif
			newtime->tm_sec += timer->interval;
			break;
	}	
	timer->nextrun = mktime(newtime);
	if (list_count(timerlist) == 0) {
		/* the list is empty, insert at the top */
		node = lnode_create_prepend(timerlist, timer);
		return;
	} else {
		if (!node) 
			node = lnode_create(timer);
		else 
			list_delete(timerlist, node);
	}		
	/* now move though the timer list and insert this at the right order */
	CurNode = list_first(timerlist);
	NextNode = list_next(timerlist, CurNode);
	while (CurNode != NULL) {
		if (CurNode) CurTimer = lnode_get(CurNode);
		if (NextNode) {
			/* if the NextNode is NULL, we are at the end of the list already */
			NextTimer = lnode_get(NextNode);
		} else {
			/* if the timer is after the CurNode, then */
			if (CurTimer->nextrun < timer->nextrun) 
				/* insert it afterwards */
				list_ins_after(timerlist, node, CurNode);
			else
				/* else insert it before */
				list_ins_before(timerlist, node, CurNode);
			/* and exit the while loop */
			break;
		}
		/* if the Curent Timer is going to run before this one */
		if (CurTimer->nextrun < timer->nextrun) {
			/* and the next timer is also going to run before this one */
			if (NextTimer->nextrun < timer->nextrun) {
				/* then Swap CurNode for NextNode */
				CurNode = NextNode;
				/* and get a new NextNode */
				NextNode = list_next(timerlist, CurNode);
			} else {
				/* otherwise insert it after the NextNode */
				list_ins_after(timerlist, node, CurNode);
				break;
			}
		} else {
			/* its before CurTimer, so insert it beforehand */
			list_ins_before(timerlist, node, CurNode);
			break;
		}
	}	
	NextSchedule();
}
Example #12
0
int mi_close(register MI_INFO *info)
{
  int error=0,flag;
  MYISAM_SHARE *share=info->s;
  DBUG_ENTER("mi_close");
  DBUG_PRINT("enter",("base: 0x%lx  reopen: %u  locks: %u",
		      (long) info, (uint) share->reopen,
                      (uint) share->tot_locks));

  mysql_mutex_lock(&THR_LOCK_myisam);
  if (info->lock_type == F_EXTRA_LCK)
    info->lock_type=F_UNLCK;			/* HA_EXTRA_NO_USER_CHANGE */

  if (info->lock_type != F_UNLCK)
  {
    if (mi_lock_database(info,F_UNLCK))
      error=my_errno;
  }
  mysql_mutex_lock(&share->intern_lock);

  if (share->options & HA_OPTION_READ_ONLY_DATA)
  {
    share->r_locks--;
    share->tot_locks--;
  }
  if (info->opt_flag & (READ_CACHE_USED | WRITE_CACHE_USED))
  {
    if (end_io_cache(&info->rec_cache))
      error=my_errno;
    info->opt_flag&= ~(READ_CACHE_USED | WRITE_CACHE_USED);
  }
  flag= !--share->reopen;
  myisam_open_list=list_delete(myisam_open_list,&info->open_list);
  mysql_mutex_unlock(&share->intern_lock);

  my_free(mi_get_rec_buff_ptr(info, info->rec_buff));
  if (flag)
  {
    DBUG_EXECUTE_IF("crash_before_flush_keys",
                    if (share->kfile >= 0) abort(););
    if (share->kfile >= 0 &&
	flush_key_blocks(share->key_cache, share->kfile,
			 share->temporary ? FLUSH_IGNORE_CHANGED :
			 FLUSH_RELEASE))
      error=my_errno;
    if (share->kfile >= 0)
    {
      /*
        If we are crashed, we can safely flush the current state as it will
        not change the crashed state.
        We can NOT write the state in other cases as other threads
        may be using the file at this point
      */
      if (share->mode != O_RDONLY && mi_is_crashed(info))
	mi_state_info_write(share->kfile, &share->state, 1);
      /* Decrement open count must be last I/O on this file. */
      _mi_decrement_open_count(info);
      if (mysql_file_close(share->kfile, MYF(0)))
        error = my_errno;
    }
#ifdef HAVE_MMAP
    if (share->file_map)
      _mi_unmap_file(info);
#endif
    if (share->decode_trees)
    {
      my_free(share->decode_trees);
      my_free(share->decode_tables);
    }
#ifdef THREAD
    thr_lock_delete(&share->lock);
    mysql_mutex_destroy(&share->intern_lock);
    {
      int i,keys;
      keys = share->state.header.keys;
      mysql_rwlock_destroy(&share->mmap_lock);
      for(i=0; i<keys; i++) {
        mysql_rwlock_destroy(&share->key_root_lock[i]);
      }
    }
#endif
    my_free(info->s);
  }
Example #13
0
int main(void)
{
    input_t in;
    list_t *l = list_create(LISTCOUNT_T_MAX);
    lnode_t *ln;
    char *tok1, *val;
    int prompt = 0;

    char *help =
        "a <val>                append value to list\n"
        "d <val>                delete value from list\n"
        "l <val>                lookup value in list\n"
        "s                      sort list\n"
        "c                      show number of entries\n"
        "t                      dump whole list\n"
        "p                      turn prompt on\n"
        "q                      quit";

    if (!l)
        puts("list_create failed");

    for (;;) {
        if (prompt)
            putchar('>');
        fflush(stdout);

        if (!fgets(in, sizeof(input_t), stdin))
            break;

        switch(in[0]) {
            case '?':
                puts(help);
                break;
            case 'a':
                if (tokenize(in+1, &tok1, (char **) 0) != 1) {
                    puts("what?");
                    break;
                }
                val = dupstring(tok1);
                ln = lnode_create(val);

                if (!val || !ln) {
                    puts("allocation failure");
                    if (ln)
                        lnode_destroy(ln);
                    free(val);
                    break;
                }

                list_append(l, ln);
                break;
            case 'd':
                if (tokenize(in+1, &tok1, (char **) 0) != 1) {
                    puts("what?");
                    break;
                }
                ln = list_find(l, tok1, comparef);
                if (!ln) {
                    puts("list_find failed");
                    break;
                }
                list_delete(l, ln);
                val = (char *) lnode_get(ln);
                lnode_destroy(ln);
                free(val);
                break;
            case 'l':
                if (tokenize(in+1, &tok1, (char **) 0) != 1) {
                    puts("what?");
                    break;
                }
                ln = list_find(l, tok1, comparef);
                if (!ln)
                    puts("list_find failed");
                else
                    puts("found");
                break;
            case 's':
                list_sort(l, comparef);
                break;
            case 'c':
                printf("%lu\n", (unsigned long) list_count(l));
                break;
            case 't':
                for (ln = list_first(l); ln != 0; ln = list_next(l, ln))
                    puts((char *) lnode_get(ln));
                break;
            case 'q':
                exit(0);
                break;
            case '\0':
                break;
            case 'p':
                prompt = 1;
                break;
            default:
                putchar('?');
                putchar('\n');
                break;
        }
    }

    return 0;
}
Example #14
0
File: list3.c Project: etoestja/inf
Data list_pop_front(struct Node * list)
{
    if(!list_is_empty(list))
        return(list_delete(list->next));
    return(0);
}
Example #15
0
/**
 * Computes the width of the graph
 */
int dag_width(struct dag *d, int nested_jobs)
{
	struct dag_node *n, *parent;
	struct dag_file *f;

	/* 1. Find the number of immediate children for all nodes; also,
	   determine leaves by adding nodes with children==0 to list. */

	for(n = d->nodes; n != NULL; n = n->next) {
		n->level = 0;	// initialize 'level' value to 0 because other functions might have modified this value.
		list_first_item(n->source_files);
		while((f = list_next_item(n->source_files))) {
			parent = f->created_by;
			if(parent)
				parent->children++;
		}
	}

	struct list *leaves = list_create();

	for(n = d->nodes; n != NULL; n = n->next) {
		n->children_remaining = n->children;
		if(n->children == 0)
			list_push_tail(leaves, n);
	}

	/* 2. Assign every node a "reverse depth" level. Normally by depth,
	   I mean topologically sort and assign depth=0 to nodes with no
	   parents. However, I'm thinking I need to reverse this, with depth=0
	   corresponding to leaves. Also, we want to make sure that no node is
	   added to the queue without all its children "looking at it" first
	   (to determine its proper "depth level"). */

	int max_level = 0;

	while(list_size(leaves) > 0) {
		struct dag_node *n = (struct dag_node *) list_pop_head(leaves);

		list_first_item(n->source_files);
		while((f = list_next_item(n->source_files))) {
			parent = f->created_by;
			if(!parent)
				continue;

			if(parent->level < n->level + 1)
				parent->level = n->level + 1;

			if(parent->level > max_level)
				max_level = parent->level;

			parent->children_remaining--;
			if(parent->children_remaining == 0)
				list_push_tail(leaves, parent);
		}
	}
	list_delete(leaves);

	/* 3. Now that every node has a level, simply create an array and then
	   go through the list once more to count the number of nodes in each
	   level. */

	size_t level_count_size = (max_level + 1) * sizeof(int);
	int *level_count = malloc(level_count_size);

	memset(level_count, 0, level_count_size);

	for(n = d->nodes; n != NULL; n = n->next) {
		if(nested_jobs && !n->nested_job)
			continue;
		level_count[n->level]++;
	}

	int i, max = 0;
	for(i = 0; i <= max_level; i++) {
		if(max < level_count[i])
			max = level_count[i];
	}

	free(level_count);
	return max;
}
Example #16
0
File: list3.c Project: etoestja/inf
Data list_pop_back(struct Node * list)
{
    if(!list_is_empty(list))
        return(list_delete(list->prev));
    return(0);
}
Example #17
0
int DEFAULT_CC
printerd_init()
{
	char filename[256];
	struct list *names;
	struct list *values;
	char *name;
	char *value;
	int index;
	int res;

	l_config = g_malloc(sizeof(struct log_config), 1);
	l_config->program_name = g_strdup("printerd");
	l_config->log_file = 0;
	l_config->fd = 0;
	l_config->log_level = LOG_LEVEL_DEBUG;
	l_config->enable_syslog = 0;
	l_config->syslog_level = LOG_LEVEL_DEBUG;

	names = list_create();
	names->auto_free = 1;
	values = list_create();
	values->auto_free = 1;
	g_snprintf(filename, 255, "%s/printerd.ini", XRDP_CFG_PATH);

	if (file_by_name_read_section (filename, PRINTERD_CFG_LOGGING, names, values) == 0) {
		for (index = 0; index < names->count; index++) {
			name = (char *)list_get_item(names, index);
			value = (char *)list_get_item(values, index);
			if (0 == g_strcasecmp(name, PRINTERD_CFG_LOG_DIR)) {
				l_config->log_file = (char *)g_strdup(value);
			}
			if (0 == g_strcasecmp(name, PRINTERD_CFG_LOG_LEVEL)) {
				l_config->log_level = log_text2level(value);
			}
			if (0 ==
			    g_strcasecmp(name, PRINTERD_CFG_LOG_ENABLE_SYSLOG)) {
				l_config->enable_syslog = log_text2bool(value);
			}
			if (0 == g_strcasecmp(name, PRINTERD_CFG_LOG_SYSLOG_LEVEL)) {
				l_config->syslog_level = log_text2level(value);
			}
		}
	}

	if (file_by_name_read_section
	    (filename, PRINTERD_CFG_GLOBAL, names, values) == 0) {
		for (index = 0; index < names->count; index++) {
			name = (char *)list_get_item(names, index);
			value = (char *)list_get_item(values, index);
			if (0 == g_strcasecmp(name, PRINTERD_CFG_GLOBAL_THREAD_COUNT)) {
				thread_count = g_atoi(value);
			}
		}
	}
	list_delete(names);
	list_delete(values);
	res = log_start(l_config);

	if (res != LOG_STARTUP_OK)
	{
		g_printf("xrdp-printerd[printerd_init]: Unable to start log system[%i]\n", res);
		return res;
	}
	else
	{
		return LOG_STARTUP_OK;
	}
}
Example #18
0
void delete_list_function()
{
    list_delete(function_list, NULL, (freedata)&delete_function);
}
Example #19
0
/*
************************************************************************************************************************
*                                    Update system tick time
*
* Description: This function is called to update system tick time.
*
* Arguments  :None
*                  
*                
*				         
*				         
* Returns   None
*				   
* Note(s) :This function is called by internal, users shoud not touch this function.
*
*             
************************************************************************************************************************
*/
void tick_list_update(void)
{
	
	LIST     *tick_head_ptr;
	RAW_TASK_OBJ            *p_tcb;
	LIST                            *iter;
	LIST                            *iter_temp;

	RAW_SR_ALLOC();

	RAW_CRITICAL_ENTER();
	
	raw_tick_count++;                                                     
	tick_head_ptr  = &tick_head;
	iter    = tick_head_ptr->next;
	
	while (RAW_TRUE) {

		/*search all the time list if possible*/
		if (iter != tick_head_ptr) {

			iter_temp =  iter->next;
			p_tcb =  raw_list_entry(iter, RAW_TASK_OBJ, tick_list);

			/*Since time list is sorted by remain time, so just campare  the absolute time*/
			if (raw_tick_count == p_tcb->tick_match) {
			
				switch (p_tcb->task_state) {
					case RAW_DLY:
						
						p_tcb->block_status = RAW_B_OK; 
						p_tcb->task_state = RAW_RDY;  
						tick_list_remove(p_tcb);
						add_ready_list(&raw_ready_queue, p_tcb);
						break; 

					case RAW_PEND_TIMEOUT:
						
						tick_list_remove(p_tcb);
						/*remove task on the block list because task is timeout*/
						list_delete(&p_tcb->task_list); 
						add_ready_list(&raw_ready_queue, p_tcb);
						p_tcb->block_status = RAW_B_TIMEOUT; 
						p_tcb->task_state = RAW_RDY; 
						
						#if (CONFIG_RAW_MUTEX > 0)
						mutex_state_change(p_tcb);
						#endif

						p_tcb->block_obj = 0;
						break;
						
					case RAW_PEND_TIMEOUT_SUSPENDED:

						tick_list_remove(p_tcb);
						/*remove task on the block list because task is timeout*/
						list_delete(&p_tcb->task_list); 
						p_tcb->block_status = RAW_B_TIMEOUT; 
						p_tcb->task_state = RAW_SUSPENDED;  
						
						#if (CONFIG_RAW_MUTEX > 0)
						mutex_state_change(p_tcb);
						#endif
					
						p_tcb->block_obj = 0;
						break;
					 
					case RAW_DLY_SUSPENDED:
										      
						p_tcb->task_state  =  RAW_SUSPENDED;
						p_tcb->block_status = RAW_B_OK; 
						tick_list_remove(p_tcb);                   
						break;

					default:
				
						port_system_error_process(RAW_SYSTEM_CRITICAL_ERROR, 0, 0, 0, 0, 0, 0);
						break;
											
				}

				iter  = iter_temp;
			}

		/*if current task time out absolute time is not equal current system time, just break because timer list is sorted*/
			else {
			
				break;

			}

		}

		
		/*finish all the time list search */ 
		
		else {
			
			break;
		}
		
	}

	RAW_CRITICAL_EXIT();
}
/*
 * Free DevCB
 */
static void delDevCB( DevCB *devcb )
{
	list_delete(&devcb->q);
	list_insert(&devcb->q, &FreeDevCB);
	devcb->devnm[0] = '\0';
}
Example #21
0
/*
====================================================================
Return a list with all accessible files and directories in path
with the extension ext (if != 0). Don't show hidden files.
Root is the name of the parent directory that can't be left. If this
is next directory up '..' is not added.
====================================================================
*/
Text* get_file_list( char *path, char *ext, char *root )
{
    Text *text = 0;
    int i, j;
    DIR *dir;
    DIR *test_dir;
    struct dirent *dirent = 0;
    List *list = 0;
    struct stat fstat;
    char file_name[512];
    FILE *file;
    int len;

    /* open this directory */
    if ( ( dir = opendir( path ) ) == 0 ) {
        fprintf( stderr, "get_file_list: can't open parent directory '%s'\n", path );
        return 0;
    }

    text = calloc( 1, sizeof( Text ) );

    /* use dynamic list to gather all valid entries */
    list = list_create( LIST_AUTO_DELETE, LIST_NO_CALLBACK );
    /* read each entry and check if its a valid entry, then add it to the dynamic list */
    while ( ( dirent = readdir( dir ) ) != 0 ) {
        /* hiden stuff is not displayed */
        if ( dirent->d_name[0] == '.' && dirent->d_name[1] != '.' ) continue;
        /* check if it's the root directory */
        if ( root )
            if ( dirent->d_name[0] == '.' )
                if ( strlen( path ) > strlen( root ) )
                    if ( !strncmp( path + strlen( path ) - strlen( root ), root, strlen( root ) ) )
                        continue;
        /* get stats */
        sprintf( file_name, "%s/%s", path, dirent->d_name );
        if ( stat( file_name, &fstat ) == -1 ) continue;
        /* check directory */
        if ( S_ISDIR( fstat.st_mode ) ) {
            if ( ( test_dir = opendir( file_name ) ) == 0  ) continue;
            closedir( test_dir );
            sprintf( file_name, "*%s", dirent->d_name );
            list_add( list, strdup( file_name ) );
        }
        else
        /* check regular file */
        if ( S_ISREG( fstat.st_mode ) ) {
            /* test it */
            if ( ( file = fopen( file_name, "r" ) ) == 0 ) continue;
            fclose( file );
            /* check if this file has the proper extension */
            if ( ext )
                if ( !strequal( dirent->d_name + ( strlen( dirent->d_name ) - strlen( ext ) ), ext ) )
                    continue;
            list_add( list, strdup( dirent->d_name ) );
        }
    }
    /* close dir */
    closedir( dir );

    /* convert to static list */
    text->count = list->count;
    text->lines = calloc( list->count, sizeof( char* ));
    for ( i = 0; i < text->count; i++ )
        text->lines[i] = strdup( (char*)list_get( list, i ) );
    list_delete( list );

    /* sort this list: directories at top and everything in alphabetical order */
    if ( text->count > 0 )
        for ( i = 0; i < text->count - 1; i++ )
            for ( j = i + 1; j < text->count; j++ ) {
                /* directory comes first */
                if ( text->lines[j][0] == '*' ) {
                    if ( text->lines[i][0] != '*' )
                        swap( &text->lines[i], &text->lines[j] );
                    else {
                        /* do not exceed buffer size of smaller buffer */
                        len = strlen( text->lines[i] );
                        if ( strlen( text->lines[j] ) < len ) len = strlen( text->lines[j] );
                        if ( strncmp( text->lines[j], text->lines[i], len ) < 0 )
                            swap( &text->lines[i], &text->lines[j] );
                    }
                }
                else {
                    /* do not exceed buffer size of smaller buffer */
                    len = strlen( text->lines[i] );
                    if ( strlen( text->lines[j] ) < len ) len = strlen( text->lines[j] );
                    if ( strncmp( text->lines[j], text->lines[i], len ) < 0 )
                        swap( &text->lines[i], &text->lines[j] );
                }
            }

    return text;
}
Example #22
0
int s3_ls_bucket(char* bucketname, struct list* dirents, const char* access_key_id, const char* access_key) {
	struct s3_message mesg;
	struct link* server = NULL;
	time_t stoptime = time(0)+s3_timeout;
	char response[HEADER_LINE_MAX];
	char path[HEADER_LINE_MAX];
	int length;
	char done = 0;

	if(!access_key_id || !access_key || !s3_endpoint) return -1;

	sprintf(path, "/");
	mesg.type = S3_MESG_GET;
	mesg.path = path;
	mesg.bucket = bucketname;
	mesg.content_type = NULL;
	mesg.content_md5 = NULL;
	mesg.content_length = 0;
	mesg.date = time(0);
	mesg.expect = 0;
	mesg.amz_headers = NULL;

	do {
		char *buffer, *temp, *start, *end;
		char trunc[25];
		int keys;
		sign_message(&mesg, access_key_id, access_key);
		
		server = s3_send_message(&mesg, server, stoptime);
		if(!server)
			return -1;

		link_readline(server, response, HEADER_LINE_MAX, stoptime);

		if(strcmp(response, "HTTP/1.1 200 OK")) {
			// Error: transfer failed; close connection and return failure
			fprintf(stderr, "Error: list bucket failed\nResponse: %s\n", response);
			link_close(server);
			return -1;
		}

		length = 0;
		do {
			if(!strncmp(response, "Content-Length:", 14)) sscanf(response, "Content-Length: %d", &length);
			if(!strcmp(response, "Transfer-Encoding: chunked")) length = 0;
			if(!strcmp(response, "Server: AmazonS3")) break;
		} while(link_readline(server, response, HEADER_LINE_MAX, stoptime));
		link_readline(server, response, HEADER_LINE_MAX, stoptime);

		if(length) {
			buffer = malloc(length+1);
			link_read(server, buffer, length, stoptime);
		} else {
			struct list *buf;
			unsigned int clen = 0;
			buf = list_create();
			do {
				link_readline(server, response, HEADER_LINE_MAX, stoptime);
				sscanf(response, "%x", &clen);
				//link_readline(server, response, HEADER_LINE_MAX, stoptime);
				if(clen) {
					buffer = malloc(clen+1);
					link_read(server, buffer, clen, stoptime);
					link_readline(server, response, HEADER_LINE_MAX, stoptime);
					list_push_tail(buf, buffer);
					length += clen;
				}
			} while(clen);
			buffer = malloc(length+1);
			buffer[0] = '\0';
			while((temp = list_pop_head(buf))) {
				sprintf(buffer, "%s%s", buffer, temp);
				free(temp);
			}
			list_delete(buf);
		}

		sscanf(buffer, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<ListBucketResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"><Name>%*[^<]</Name><Prefix></Prefix><Marker></Marker><MaxKeys>%d</MaxKeys><IsTruncated>%[^<]</IsTruncated>", &keys, trunc);
		if(!strcmp(trunc, "false")) done = 1;
		temp = buffer;
		while( (start = strstr(temp, "<Contents>")) ) {
			struct s3_dirent_object *dirent;
			struct tm date;
			char display_name[1024];
			end = strstr(start, "</Contents>");
			end[10] = '\0';
			temp = end + 11;
			dirent = malloc(sizeof(*dirent));
			date.tm_isdst = -1;
			sscanf(strstr(start, "<Key>"), "<Key>%[^<]</Key>", dirent->key);
			sscanf(strstr(start, "<LastModified>"), "<LastModified>%d-%d-%dT%d:%d:%d.%*dZ</LastModified>", &date.tm_year, &date.tm_mon, &date.tm_mday, &date.tm_hour, &date.tm_min, &date.tm_sec);
			sscanf(strstr(start, "<ETag>"), "<ETag>&quot;%[^&]&quot;</ETag>", dirent->digest);
			sscanf(strstr(start, "<Size>"), "<Size>%d</Size>", &dirent->size);
			sscanf(strstr(start, "<Owner>"), "<Owner><ID>%*[^<]</ID><DisplayName>%[^<]</DisplayName></Owner>", display_name);
			if(strlen(display_name)) dirent->display_name = strdup(display_name);
			date.tm_mon -= 1;
			dirent->last_modified = mktime(&date);
			list_push_tail(dirents, dirent);
		}
		free(buffer);

	} while(!done);

	link_close(server);
	return 0;
}
Example #23
0
void *client_handler(void *fd) {
	struct THREADINFO threadinfo = *(struct THREADINFO *)fd;
	struct PACKET packet;
	struct LLNODE *curr;
	int bytes, sent;
	while(1) {
		bytes = recv(threadinfo.sockfd, (void *)&packet, sizeof(struct PACKET), 0);
		if(!bytes) {
			fprintf(stderr, "Connection lost from [%d] %s...\n", threadinfo.sockfd, threadinfo.alias);
			pthread_mutex_lock(&clientlist_mutex);
			list_delete(&client_list, &threadinfo);
			pthread_mutex_unlock(&clientlist_mutex);
			break;
		}
		printf("[%d] %s %s %s\n", threadinfo.sockfd, packet.option, packet.alias, packet.buff);
		if(!strcmp(packet.option, "alias")) {
			printf("Set alias to %s\n", packet.alias);
			pthread_mutex_lock(&clientlist_mutex);
			for(curr = client_list.head; curr != NULL; curr = curr->next) {
				if(compare(&curr->threadinfo, &threadinfo) == 0) {
					strcpy(curr->threadinfo.alias, packet.alias);
					strcpy(threadinfo.alias, packet.alias);
					break;
				}
			}
			pthread_mutex_unlock(&clientlist_mutex);
		}
		else if(!strcmp(packet.option, "whisp")) {
			int i;
			char target[ALIASLEN];
			for(i = 0; packet.buff[i] != ' '; i++); packet.buff[i++] = 0;
			strcpy(target, packet.buff);
			pthread_mutex_lock(&clientlist_mutex);
			for(curr = client_list.head; curr != NULL; curr = curr->next) {
				if(strcmp(target, curr->threadinfo.alias) == 0) {
					struct PACKET spacket;
					memset(&spacket, 0, sizeof(struct PACKET));
					if(!compare(&curr->threadinfo, &threadinfo)) continue;
					strcpy(spacket.option, "msg");
					strcpy(spacket.alias, packet.alias);
					strcpy(spacket.buff, &packet.buff[i]);
					sent = send(curr->threadinfo.sockfd, (void *)&spacket, sizeof(struct PACKET), 0);
				}
			}
			pthread_mutex_unlock(&clientlist_mutex);
		}
		else if(!strcmp(packet.option, "send")) {
			pthread_mutex_lock(&clientlist_mutex);
			for(curr = client_list.head; curr != NULL; curr = curr->next) {
				struct PACKET spacket;
				memset(&spacket, 0, sizeof(struct PACKET));
				if(!compare(&curr->threadinfo, &threadinfo)) continue;
				strcpy(spacket.option, "msg");
				strcpy(spacket.alias, packet.alias);
				strcpy(spacket.buff, packet.buff);
				sent = send(curr->threadinfo.sockfd, (void *)&spacket, sizeof(struct PACKET), 0);
			}
			pthread_mutex_unlock(&clientlist_mutex);
		}
		else if(!strcmp(packet.option, "exit")) {
			printf("[%d] %s has disconnected...\n", threadinfo.sockfd, threadinfo.alias);
			pthread_mutex_lock(&clientlist_mutex);
			list_delete(&client_list, &threadinfo);
			pthread_mutex_unlock(&clientlist_mutex);
			break;
		}
		else {
			fprintf(stderr, "Garbage data from [%d] %s...\n", threadinfo.sockfd, threadinfo.alias);
		}
	}
	 
	/* clean up */
	close(threadinfo.sockfd);
	 
	return NULL;
}
Example #24
0
void options_end(void)
{
  list_foreach(options.exclude_list, free_list_elems_cb, NULL);
  list_delete(options.exclude_list);
}
Example #25
0
lnode_t *list_del_first(list_t *list)
{
    return list_delete(list, list->nilnode.next);
}