Ejemplo n.º 1
0
int main()
{
	
	listInsert(1); 
	listInsert(1);
	listInsert(1);
	listInsert(3);
  listInsert(3);
	listInsert(3);
	listInsert(3);
	listInsert(3);
	listInsert(9);
						
	std::cout << "Inserted elements into list" << std::endl;


  Node* curr = head;
  while(curr) {
  	std::cout << " " << curr->value;
  	curr = curr->next;
  }
  
  removeDuplicates();
  std::cout << std::endl << "Removed duplicate elements in first list" << std::endl;

  curr = head;
  while(curr) {
  	std::cout << " " << curr->value;
  	curr = curr->next;
  }
  
}
Ejemplo n.º 2
0
int Graph::MaxFlow(int s, int t) 
{    
   flownode *L; 
   flownode *itr; 
   int i, u, oldheight; 
   //构造每个结点的Neightbour list; 
   for(u = 0; u < V; ++u) 
   { 
      N[u] = new flownode; 
      N[u]->next = NULL;       
   } 
   for(u = 0; u < V; ++u) 
   { 
      for(i = 0; i < u; ++i) 
         if( c[u][i] || c[i][u] ) 
         { 
            listInsert(N[u],i); 
            listInsert(N[i],u); 
         } 
   } 
   //构造L 
   L = new flownode; 
   L ->next = NULL; 
   for( i = 0; i < V; ++i) 
   { 
      if(i == s || i == t) continue; 
      listInsert(L,i); 
   } 
   //初始化preflow 
   InitializePreflow(s); 
   // 
    
   for(itr = L; itr->next; itr = itr->next ) 
   { 
      u = itr->next->adjnum; 
      oldheight = h[u]; 
      DischargePreflow(u); 
      if(h[u] > oldheight) 
      { 
         listErase(itr); 
         listInsert(L,u); 
         itr = L; 
      } 
   } 
   listDestroy(L); 
   maxflow = 0; 
   for( itr = N[s]->next; itr; itr = itr->next) 
   { 
      if(f[s][itr->adjnum]  ) 
         maxflow += f[s][itr->adjnum]; 
   } 
   neighborDestroy(); 
   return maxflow; 
} 
Ejemplo n.º 3
0
void testInserts() {
    // Create the list
    LList *list = newList( comparisonFunction );
    const int numElements = 100;
    int prevSize = list->size;

    // Insert a bunch of elements into the list
    for( int i = 1; i <= numElements; i++ ) {
        listInsert( list, mallocInt(i) );
        assertTrue( (prevSize + 1) == list->size, "List size should have increased by 1\n" );
        prevSize++;
    }

    // Assert that the right number of elements are present in the list
    assertTrue( numElements == list->size, "List should now have %d elements, has %d\n",
            numElements, list->size );

    // Check that the ordering invariant holds
    ListNode *current = list->head;
    ComparisonFunction compare = list->comparisonFunction;
    int numElementsCompared = 0;
    while( current->next != NULL ) {
        void *nodeData = current->data;
        void *nextNodeData = current->next->data;

        // Segfault prevention check
        if( nodeData != NULL && nextNodeData != NULL ) {
            int comparisonResult = compare(nodeData, nextNodeData);
            assertTrue( comparisonResult < 0, "Assert comparisonResult < 0 failed! (Was %d)\n",
                    comparisonResult );

            numElementsCompared++;
        }

        current = current->next;
    }

    // Ensure that we made some value comparisons throughout the the loop
    assertTrue( numElementsCompared != 0, "Should haven't compared more than 0 elements!\n" );

    // Test insert at beginning
    listInsert( list, mallocInt( -1 ) );

    // Test insert at end
    listInsert( list, mallocInt( 1000 ) );

    // Free the list
    listFree( list );
}
Ejemplo n.º 4
0
//Initializes Player using starting Values
void initPlayer(Player *p){
    *p=(Player){
        startSpeedDig,
        startSpeedWalk,
        startMaxDepth,
        startInventorySize,
        startMoney
    };
    listInsert(&p->inventory, &shoesStart);
    listInsert(&p->inventory, &pickaxeStart);
    listInsert(&p->inventory, &backpackStart);

    //Initialize Mineral-Array
    memset(p->minerals, 0, sizeof(p->minerals));
}
Ejemplo n.º 5
0
Archivo: inLib.c Proyecto: phoboz/vmx
int in_pcballoc(struct socket *so, struct inpcbinfo *pcbinfo)
{
  struct inpcb *inp;
  int s;

  inp = mb_alloc( sizeof(struct inpcb), MT_PCB, M_DONTWAIT);
  if (inp == NULL)
    return ENOBUFS;

  /* Clear struct */
  memset( inp, 0, sizeof(struct inpcb) );

  /* Setup struct */
  inp->inp_pcbinfo = pcbinfo;
  inp->inp_socket = so;

  /* Get processor level */
  s = splnet();

  /* Insert into info list head */
  listInsert(pcbinfo->listhead, NULL, &inp->inp_list);
  in_pcbinshash(inp);

  /* Restore processor level */
  splx(s);

  /* Setup address */
  so->so_pcb = inp;

  return 0;
}
Ejemplo n.º 6
0
int main()
{
	struct listItem* start = NULL; 
	struct listItem* newItem = calloc(1U, sizeof(*newItem));
	struct listItem* item1   = calloc(1U, sizeof(*item1));

	(*newItem).data = 11; // dereference ptr, to get to listItem struct and access .data element.
	(*item1).data   = 22;
	start = newItem;

	printf("&start address in main: %p\n", &start);
	printf("start address in main: %p\n", start);
	printf("*start address in main: %p\n\n\n", *start);	

	listInsert(&start, item1); 
    //listInsert(start, item1);

	printf("item1->data: %d\n", item1->data);

	struct listItem* current = start;
	size_t numberOfElements = 0;

	while (current) {
		printf("%d\n", (*current).data);
		current = (*current).next;
		++numberOfElements;
	}

	printf("numberOfElements: %lu\n", numberOfElements);
}
Ejemplo n.º 7
0
char * intProccess(char * s) {/*{{{*/
	StrInputStream ssin;
	// StrOutputStream ssout;
	LinkedList * l = createLinkedList(sizeof(int), intGreater);

	int x;
	initStrInputStream(&ssin, s);
	initStrOutputStream(&ssout, 250);
	// printf("%d\n", (ssout.length));

	while (!sisEof(&ssin)) {
		readInt(&ssin, &x);
		if (listSearch(l, &x) == l->nil) {
			ListNode * a = l->nil->next;

			while (a != l->nil && *((int *)(a->key)) < x) {
				a = a->next;
			}

			listInsert(l, a, &x);
		}
	}

	listTravers(l, putInt);
	clrListedList(l, NULL);
	writeString(&ssout, "\n");
	return ssout.begin;
}/*}}}*/
Ejemplo n.º 8
0
Archivo: bio.c Proyecto: phoboz/vmx
void brelse (
    struct buf * bp
    ) {
    LIST *pBufHead = &bp->b_vp->v_mount->mnt_buflist;

    if ((bp->b_flags & B_BUSY) == 0) {
#ifdef DIAGNOSTIC
        logMsg ("brelse: buffer is not busy",
                0, 0, 0, 0, 0, 0);
#endif
        return;
    }
    
    /* anyone need this very block? */
    if (bp->b_flags & B_WANTED) {
        bp->b_flags &= ~B_WANTED;
        semGive (&bp->b_sem);
    }

    /* Put buffer at head */
    listRemove (pBufHead, &bp->b_node);        /* Remove from list */
    listInsert (pBufHead, NULL, &bp->b_node);  /* Insert at list head */

    /* unlock */
    bp->b_flags &= ~(B_WANTED | B_BUSY | B_ASYNC);
}
Ejemplo n.º 9
0
void testRemoval() {
    LList *list = newList( comparisonFunction );
    const int numElements = 1000;

    // Insert elements
    for( int i = 0; i < numElements; i++ ) {
        listInsert( list, mallocInt(i) );
    }

    // Remove the elements and ensure that the right elements were removed
    for( int i = 0; i < numElements; i++ ) {
        int *elementToRemove = mallocInt(i);
        int *removedElement = listRemove( list, elementToRemove );

        assertNotNull( removedElement, "removedElement is null!\n" );

        int comparisonResult = list->comparisonFunction( elementToRemove, removedElement );
        assertTrue( comparisonResult == 0, "compare(%d, %d) != 0\n", *elementToRemove,
                *removedElement );

        free( elementToRemove );
        free( removedElement );
    }

    // Free the list
    listFree( list );
}
Ejemplo n.º 10
0
void testListFind() {
    LList *list = newList( comparisonFunction );
    const int numElements = 1000;

    // Insert the elements
    for( int i = 0; i < numElements; i++ ) {
        listInsert( list, mallocInt(i) );
    }

    // Find the elements
    for( int i = 0; i < numElements; i++ ) {
        int *intToFind = mallocInt(i);

        // Ensure that the find didn't return null
        ListNode *findResult = listFind( list, intToFind );
        assertNotNull( findResult, "find(i) should not be NULL!\n" );

        // Ensure that the elements are equal
        int comparisonResult = list->comparisonFunction( intToFind, findResult->data );
        assertTrue( comparisonResult == 0, "find(%d)->data != %d\n", i, i );

        free( intToFind );
    }

    // Free the list
    listFree( list );
}
Ejemplo n.º 11
0
Archivo: bio.c Proyecto: phoboz/vmx
int buf_wait (
    struct buf * bp
    ) {
    LIST *pBufHead = &bp->b_vp->v_mount->mnt_buflist;

    /* Make sure I/O is complete */
    if ((bp->b_flags & B_DONE) == 0) {
        if (bio_wait (bp->b_bio)) {
            bp->b_flags |= B_ERROR;
        }
        buf_done (bp, OK);
    }

    if ((bp->b_flags & B_ERROR) || bp->b_error) {
        if ((bp->b_flags & B_INVAL) == 0) {
            bp->b_flags |= B_INVAL;
            listRemove (pBufHead, &bp->b_node);        /* Remove from list */
            listInsert (pBufHead, NULL, &bp->b_node);  /* Insert at list head */
        }
        if (!bp->b_error) {
            bp->b_error = EIO;
        } else {
            bp->b_flags |= B_ERROR;
        }
        return (bp->b_error);
    } else {
        return (OK);
    }
}
Ejemplo n.º 12
0
Archivo: main.c Proyecto: mfdeakin/heap
void cmdInsert(heap *ops, bool print)
{
	if(print)
		printf("String: ");
	char *buf = NULL;
	list *strbuf = listCreate();
	for(;;) {
		buf = malloc(sizeof(*buf));
		fread(buf, sizeof(*buf), 1, stdin);
		if(*buf == '\n')
			break;
		listInsert(strbuf, buf);
	}
	free(buf);
	int listsize = listSize(strbuf),
		i;
	buf = malloc(sizeof(char[listsize + 1]));
	memset(buf, 0, sizeof(char[listsize + 1]));
	for(i = 0, listMoveBack(strbuf);
			i < listsize;
			i++, listMoveBack(strbuf)) {
		char *tmp = listGetCurrent(strbuf);
		buf[i] = *tmp;
		free(tmp);
	}
	listFree(strbuf);
	hpAdd(ops, buf);
}
Ejemplo n.º 13
0
void listInsert(struct entityList *list, struct entity ent)
{
	if(list->next == NULL){
		list->next = (struct entityList*) malloc(sizeof(struct entityList));
	}else{
		listInsert(list->next, ent);
	}

}
Ejemplo n.º 14
0
void listTest(void)
{
    List *list;
    int i;

    list = createList();

    printf("delete when list is empty\n");
    listDelete(list, 0);

    printf("insert 0\n");
    listInsert(list, 0, 0);
    listTraverse(list);

    printf("delect position:0\n");
    listDelete(list, 0);
    listTraverse(list);
    
    printf("insert 5 element to list\n");
    for(i = 0; i < 5; i++) {
        listInsert(list, 5 - i, 0);
    }
    listTraverse(list);

    printf("insert 55 to position 3\n");
    listInsert(list, 55, 3);
    listTraverse(list);

    printf("delete first tree element\n");
    for(i = 0; i < 3; i++) {
        listDelete(list, 0);
    }
    listTraverse(list);

    printf("delete position 1\n");
    listDelete(list, 1);
    listTraverse(list);

    printf("get position 3\n");
    printf("postion 3:%d\n", listGet(list, 3));

    destroyList(list);
}
Ejemplo n.º 15
0
 //добавляет узел в конец списка, возвращает указатель на него
 //O(1)
 ListNode* listPushBack(ListNode** list) {
     if(*list)
         return listInsert(*list);
     //если список пуст, создаём новый список
     ListNode* ln = malloc(1);
     ln->next = ln->prev = ln;
     ln->data = NULL;
     *list = ln;
     return *list;
 }
int main(void) {
  unsigned ind;
  listInit();
  for (ind = 0; ind < MAX; ind++)
    listInsert(rand() % (MAX*2), ind);
  printf("Списъкът съдържа следните елементи: \n"); listPrint();
  printf("\nТестване:\n");
  performSearchTest();
  printf("Списъкът след търсенето: \n"); listPrint();
  return 0;
}
Ejemplo n.º 17
0
int main(int argc, char* argv[])
{
    head_ptr ls_head = (head_ptr)malloc(sizeof(head));
    ls_head->head = NULL;

    list ele_x1;
    ele_x1.key = 1;
    list ele_x2;
    ele_x2.key = 4;
    list ele_x3;
    ele_x3.key = 16;
    list ele_x4;
    ele_x4.key = 9;
    
    listInsert(ls_head, &ele_x1);
    listInsert(ls_head, &ele_x2);
    listInsert(ls_head, &ele_x3);
    listInsert(ls_head, &ele_x4);
    printList(ls_head);

    list_ptr ele_find = listSearch(ls_head, 4);
    if (ele_find != NULL)
        printf("find element of key in 4\n");
    else
        printf("find not element of key in 4\n");
    
    list ele_x5;
    ele_x5.key = 25;
    listInsert(ls_head, &ele_x5);
    printList(ls_head);

    if (ele_find != NULL) {
        listDelete(ls_head, ele_find);
        printList(ls_head);
    }

    free(ls_head);
    ls_head = NULL;
    return 0;
}
Ejemplo n.º 18
0
//Buys an Item, returns true if successful
bool itemBuy(Player *p, Item *i){
    //Check if Item is already owned
    if(listCount(&p->inventory, i) >= 1 ) return false;
    int newmoney = p->money - i->prize;
    int newspace = getFreeInvSpace(p) - i->inventorySizeTaken;
    if( newmoney >= 0 && newspace >= 0){
        p->money = newmoney;
        listInsert(&p->inventory, i);
        updateItems(p);
        return true;
    }
    return false;
}
Ejemplo n.º 19
0
/*
 * Arrange for <cb> to be called at time <t>, which is the (double precision floating point) number
 * of seconds since 00:00:00 UTC on 1970-01-01 (aka. the UNIX epoch). <cb> will be called with the
 * given <dis>, <t> and <udata>. You can get the current time using nowd() from utils.c.
 */
void disOnTime(Dispatcher *dis, double t, void (*cb)(Dispatcher *dis, double t, void *udata), const void *udata)
{
    DIS_Timer *next_timer, *new_timer = calloc(1, sizeof(DIS_Timer));

    new_timer->t = t;
    new_timer->cb = cb;
    new_timer->udata = udata;

    for (next_timer = listHead(&dis->timers); next_timer; next_timer = listNext(next_timer)) {
        if (next_timer->t > new_timer->t) break;
    }

    listInsert(&dis->timers, new_timer, next_timer);
}
Ejemplo n.º 20
0
// listInsert: insert into a linked list, overwrites duplicate keys
nodeType *listInsert(nodeType *head, unsigned long long int key, unsigned long int value) {
	if (!head) {
		head = malloc(sizeof(nodeType));
		head->key = key;
		head->value = value;
		head->next = NULL;
	}
	else if (head->key != key)
		head->next = listInsert (head->next, key, value);
	else
		head->value = value;

	return head;
}
Ejemplo n.º 21
0
/*
 * store & intern a prefix, after giving it the
 *  "xmlns:" prefix.  Don't allow storing the same one twice unless 'force'
 *  is set.
 */
static utf8 storePrefix(genxWriter w, constUtf8 prefix, Boolean force)
{
  int high, low;
  utf8 * pp = (utf8 *) w->prefixes.pointers;
  UTFTYPE buf[1024];

  if (prefix[0] == 0)
    prefix = (utf8) "xmlns";
  else
  {
    sprintf((char *) buf, "xmlns:%s", prefix);
    prefix = buf;
  }

  high = w->prefixes.count; low = -1;
  while (high - low > 1)
  {
    int probe = (high + low) / 2;
    if (strcmp((const char *) prefix, (const char *) pp[probe]) < 0)
      high = probe;
    else
      low = probe;
  }

  /* already there? */
  if (low != -1 && strcmp((const char *) prefix, (const char *) pp[low]) == 0)
  {
    if (force)
      return pp[low];

    w->status = GENX_DUPLICATE_PREFIX;
    return NULL;
  }

  /* copy & insert */
  if ((prefix = copy(w, prefix)) == NULL)
  {
    w->status = GENX_ALLOC_FAILED;
    return NULL;
  }
  
  w->status = listInsert(&w->prefixes, (void *) prefix, high);
  if (w->status != GENX_SUCCESS)
    return NULL;

  return (utf8) prefix;
}
Ejemplo n.º 22
0
Archivo: world.c Proyecto: phoboz/yz
static FIELD* add_world_field(
  WORLD *world,
  int tx,
  int ty,
  int tw,
  int th
  )
{
  static int id;
  FIELD *field;
  int i, j, ie, je;

  if (tx < 2 || tx > world->map->w - 2 ||
      ty < 2 || ty > world->map->h - 2)
    return NULL;

  if (tx + tw > world->map->w - 2 ||
      ty + th > world->map->h - 2)
    return NULL;

  field = (FIELD *) malloc( sizeof(FIELD) );
  if (field == NULL) {

    fprintf(stderr, "Error - Unable to allocate field\n");
    exit(1);

  }

  field->x = tx;
  field->y = ty;
  field->w = tw;
  field->h = th;
  field->level = tw * th / 8;
  field->id = id++;

  listInsert(&world->fieldList, NULL, &field->listNode);

  ie = field->x + field->w;
  je = field->y + field->h;

  for (j = field->y; j < je; j ++)
    for (i = field->x; i < ie; i ++)
      world->world_map[i + j * world->map->w] = WORLD_FIELD_BLOCK;

  return field;
}
Ejemplo n.º 23
0
Archivo: bio.c Proyecto: phoboz/vmx
struct buf* buf_getblk (
    struct vnode * vp,
    lblkno_t       blkno,
    unsigned       size
    ) {
    struct buf *bp;
    LIST *pBufHead = &vp->v_mount->mnt_buflist;

loop:
    if ((bp = buf_incore (vp, blkno)) != NULL) {
        if (bp->b_flags & B_BUSY) {
            bp->b_flags |= B_WANTED;
            semTake (&bp->b_sem, WAIT_FOREVER);
        }
        bp->b_flags |= (B_BUSY | B_CACHE);
        /*
         * check for size inconsistancies
         */
        if (bp->b_size != size) {
            logMsg ("getblk: invalid buffer size: %d\n",
                    (ARG) bp->b_size,
                    0, 0, 0, 0, 0);
            bp->b_flags |= B_INVAL;
            bwrite (bp);
            goto loop;
        }
    } else {
        if ((bp = buf_new (vp, blkno)) == NULL) {
            logMsg ("buf_getblk: no buffers",
                    0, 0, 0, 0, 0, 0);
            goto loop;
        }
        bp->b_dev = vp->v_mount->mnt_dev;
        bp->b_lblkno = blkno;
        bp->b_vp = vp;
        bio_new (bp);
        
        /* Put buffer at head */
        listRemove (pBufHead, &bp->b_node);
        listInsert (pBufHead, NULL, &bp->b_node);
    }

    return (bp);
}
Ejemplo n.º 24
0
int main(int argc, char *argv[])
{

  pthread_t the_reader[READERS];
  int i, random;
  time_t start_time, end_time;
  
  // initialize the counters
  found = 0;
  not_found = 0;
  
  // record the start time
  start_time = time(NULL);

  // initialize the concurrent list
  listInit(&the_list);
  
  // create the reader threads
  for (i = 0; i < READERS; i++)
  {
    pthread_create(&the_reader[i], NULL, reader, NULL);
  }

  // start writing to the list
  for (i = 0; i < NUMWRITES; i++)
  {
    random = randInt(KEYMIN,KEYMAX);
    listInsert(&the_list, random, random);
  }

  // wait for the reader threads
  for (i = 0; i < READERS; i++)
  {
    pthread_join(the_reader[i], NULL);
  }

  // print the time taken and the counter values
  end_time = time(NULL);
  printf("%d items were found. %d items were not found.\n\tTime taken: %d seconds.", found, not_found, end_time-start_time);
  
  
  printf("\nEnd of processing\n");
  return 0;
} /* end main */
void parseSection(MFILE *mfout, const char *params)
{
	char *name=(char*)params, *comment=strchr(params, ' '), *cend;
	
	if(secakt!=NULL)
		mfprintf(mfout, "\n\";\n");

	if(comment!=NULL) {
		*comment=0;
		comment++;
		if(comment[0]!=0 && comment[0]!='\'')
			pexit("Section-Comment not started with ' - exiting\n", params);
		comment++;
		cend=strchr(comment, '\'');
		if(cend==NULL) pexit("Section-Comment not ended with ' - exiting\n", params);
		*cend=0;
	}
	
	secakt=listInsert(name, comment);
	mfprintf(mfout, "\nconst char %s[]=\"", name);
}
Ejemplo n.º 26
0
int main(int argc, char **argv) {
	//Establish anything we'll need constantly.
	int mode = 1;//Start in sequential mode.
	int usepath = 0;//does our path file exist?
	int futuremode = mode;//This keeps track of mode changes until the end of the line.
	int printPrompt = 0;
	char *prompt = "s-term> ";//The prompt string.
	printf("%s", prompt);//Print the prompt.
	fflush(stdout);
 
	//do pathstuff
	char **paths = readFile("shell-config");
	if(paths != NULL){
		usepath = 1;
	}

	char **firststep = NULL;//The array of commands made by splitting the buffer along semicolons.
	char ***secondstep = NULL;//The array of commands, with each command split along whitespace into its arguments.
		
	struct node *head = NULL;//The head of the linked list of ongoing jobs.
	
	char buffer[1024];//The buffer.
	while (1) {//
		struct pollfd pfd = {0, POLLIN};
		if(printPrompt){
			//Need to reprint the prompt.
			printf("%s",prompt);
			fflush(stdout);
			printPrompt = 0;
		}
		int rv = poll(&pfd, 1, 1000);
		if (rv==0){
			//No change, use time to do other tasks
			struct node *anode = head;
			while(anode != NULL){
				int pstatus = 0;
				int pstate = waitpid((*anode).pid,&pstatus,WNOHANG);
				if(pstate>0){
					//Process has returned; print confirmation message and delete this node.
					printf("Command %s, id %i was executed.\n",(*anode).command, anode->pid);
					anode = (*anode).next;
					listDelete(pstate, &head);
					printPrompt = 1;
				} else if(pstate<0){
					//Error in waitpid, print error message and break from while loop.
					printf("Error retrieving process status.\n");
					break;
				} else{
					//Process has not returned.
					anode = (*anode).next;
				}
			}
		} else if (rv < 0){
			//Poll went horribly wrong and we're bailing out of the flaming wreckage, screaming at the tops of our lungs.
			printf("Polling error; shutting the (s)hell down.");
		} else {
			//Keyboard I/O
			if(fgets(buffer, 1024, stdin) != NULL){

				mode = futuremode;//Ensure that mode is up-to-date.

				//Remove any comments after a hash.
				removeComment(buffer);
		
				//Tokenize buffer by semicolons- each will be an executable command.
		
				firststep = tokenify(buffer,";");
				secondstep = tokenify2(firststep," \t\n");

				//Free firststep, as it is no longer needed. Free the sub-arrays first, then the array proper.
				freeAll1(firststep);
				free(firststep);
	
				int j = 0;
				int futureExit = 0;
				int status = 0;
				pid_t p = 1;

				//Execute all commands in a loop.
				while(secondstep[j] !=  NULL && secondstep[j][0] != NULL){
					//check for the special commands mode or exit. If neither of these, fork and execv.
					if(!strcasecmp(secondstep[j][0],"exit")){
						int canwequit = 1;
						struct node *tmp = head;
						while(tmp != NULL){
							if(tmp->state != 1){
								canwequit = 0;
							}
							tmp = tmp->next;
						}
						if (canwequit){
							futureExit = 1;//Will be checked at the end of the loop.
						} else {
							printf("Error: Jobs are currently running. Please wait for tasks to finish before exiting.\n");
						}
					}
					else if(!strcasecmp(secondstep[j][0],"pause")){
						setState(atoi(secondstep[j][1]), 1, head);
						if(kill(atoi(secondstep[j][1]), SIGSTOP) != -1){
							printf("Paused process %i\n",atoi(secondstep[j][1]));
						}
						else{
							printf("Something went terribly wrong\n");
						}
						
					}
					else if(!strcasecmp(secondstep[j][0],"resume")){
						setState(atoi(secondstep[j][1]), 0, head);
						if(kill(atoi(secondstep[j][1]), SIGCONT) != -1){
							printf("Resumed process %i\n",atoi(secondstep[j][1]));
						}
					}
					else if(!strcasecmp(secondstep[j][0],"jobs")){
						struct node *tmp = head;
						printf("\npid cmd paused\n");
						while(tmp != NULL){
							printf("%i %s %i\n",tmp->pid,tmp->command,tmp->state);
							tmp = tmp->next;
						}
					}
					/*else if(!strcasecmp(secondstep[j][0],"path")&& !strcasecmp(secondstep[j][1],"refresh")){
						if(paths != NULL){
						freeAll1(paths);
						free(paths);
						}
						//do pathstuff
						char **paths = readFile("shell-config");
						if(paths == NULL){
							usepath = 0;
						}else{
							usepath = 1;
						}
					}*/
					else if(!strcasecmp(secondstep[j][0],"MODE")){
						if(secondstep[j][1] == NULL){
							if(mode == 0){
								printf("\nCurrent mode is parallel\n");
							}
							else {
								printf("\nCurrent mode is sequential\n");
							}
						}
						else if(!strcasecmp(secondstep[j][1],"PARALLEL") || !strcasecmp(secondstep[j][1],"p")){
							futuremode = 0;
						}
						else if(!strcasecmp(secondstep[j][1],"SEQUENTIAL") || !strcasecmp(secondstep[j][1],"s")){
							futuremode = 1;
						}
						else {
							//Bullshit users with their bullshit commands - throw an error.
							printf("\nError: Your command was pretty awful.\n");
						}
					}
					else{
						//Fork and execute/wait depending on process id.
						p = fork();
						if (p == 0){
							break;//Child processes handled outside the while loop.
						}
						if(mode==1){//Sequential mode.
							wait(&status);
							//Do something with childp; error checking, probably
						} else {//Parallel mode; add this to the list
							listInsert(p, secondstep[j][0], 0, &head);
						}
					}
					j++;
				}
		
				if (p == 0){
					if(usepath==1){
						int k = 0;
						while(paths[k] != NULL){
							struct stat sr;
							char tempbuffer[1024];
							strcpy(tempbuffer, paths[k]);
							strcat(tempbuffer, "/");
							strcat(tempbuffer, secondstep[j][0]);
							int rv = stat(tempbuffer, &sr);
							if (rv < 0){
								k++;
							}	
							else{
								secondstep[j][0]=tempbuffer;
								if(execv(secondstep[j][0],secondstep[j])<0){
									exit(0);
								}
							}
						}
					}
					//Execv for an actual, non-hardcoded command.
					printf("\n%s\n",secondstep[j][0]);
					if(execv(secondstep[j][0],secondstep[j])<0){
						fprintf(stderr, "Your command failed, and here's why you're a bad person: %s\n", strerror(errno));
					}
					exit(0);//Close out the child process corpse.
		
				} 
				
				//check if there was an exit command earlier
				if(futureExit == 1){
					break;
				}

				//If we don't exit, free current buffer
				freeAll2(secondstep);	
				free(secondstep);
		
				//Make sure firststep and secondstep have an assigned value in case of early termination.
				firststep = NULL; 
				secondstep = NULL;
		
				printf("%s", prompt);
				fflush(stdout);
				}
			if(feof(stdin)){
				break;//End of file or Ctrl+D
			}
			}
		}
	//on a quit, flush our command array if it's not null already
	if(secondstep != NULL){
		freeAll2(secondstep);
		free(secondstep);
	}
		
	//Free the paths array as well.
	if(paths!=NULL){
		freeAll1(paths);
		free(paths);
	}
		
	//Check time spent in user mode and kernel mode. Right now I've got it separated by shell and processes, but we can add it together later.
	int idParent = RUSAGE_SELF;
	int idChild = RUSAGE_CHILDREN;
	int statParent = 0;
	int statChildren = 0;
	struct rusage dataParent;
	struct rusage dataChildren;
	statParent = getrusage(idParent, &dataParent);
	statChildren = getrusage(idChild, &dataChildren);
	if(!statParent){//If the getrvalue operation was a success
		printf("Shell time in user mode: %ld.%06ld seconds.\n", dataParent.ru_utime.tv_sec, dataParent.ru_utime.tv_usec);
		printf("Shell time in kernel mode: %ld.%06ld seconds. \n", dataParent.ru_stime.tv_sec, dataParent.ru_stime.tv_usec);
	}
	if(!statChildren){
		printf("Process time in user mode: %ld.%06ld seconds. \n", dataChildren.ru_utime.tv_sec, dataChildren.ru_utime.tv_usec);
		printf("Process time in kernel mode: %ld.%06ld seconds. \n", dataChildren.ru_stime.tv_sec, dataChildren.ru_stime.tv_usec);
	}
	exit(0);
	//Ctrl+D will drop you down here; need to make sure any cleanup also happens here too.
	return 0;
}
Ejemplo n.º 27
0
Archivo: kp8.c Proyecto: BlagoProg/MAI
int main(void)
{
	const int N = 10;
	int i, isFound, action, pos, arg;
	List list;
	Iterator it;

	listCreate(&list, N);

	do
	{
		printf("Меню:\n");
		printf("1) Вставить элемент\n");
		printf("2) Удалить элемент\n");
		printf("3) Печать списка\n");
		printf("4) Размер списка\n");
		printf("5) Выполнить задание над списком\n");
		printf("6) Выход\n");
		printf("Выберите действие: ");
		scanf("%d", &action);

		switch (action)
		{
			case 1:
			{
				printf("Введите позицию элемента: ");
				scanf("%d", &pos);
				printf("Введите значение элемента (1 - true, 0 - false): ");
				scanf("%d", &arg);

				if (arg != 0 && arg != 1)
					printf("Ошибка. Введено недопустимое значение\n");
				else
					listInsert(&list, pos - 1, arg);

				break;
			}

			case 2:
			{
				printf("Введите номер элемента: ");
				scanf("%d", &pos);

				listRemove(&list, pos - 1);

				break;
			}

			case 3:
			{	
				listPrint(&list);

				break;
			}

			case 4:
			{
				printf("Длина списка: %d\n", listSize(&list));

				break;
			}

			case 5:
			{
				printf("Введите значение: ");
				scanf("%d", &arg);
				
				if (arg != 0 && arg != 1)
					printf("Ошибка. Введено недопустимое значение\n");
				else
				{
					it = itFirst(&list);

					isFound = 0;

					for (i = 0; i < listSize(&list); i++)
					{
						if (itFetch(&it) == arg)
						{
							while (!listEmpty(&list))
								listRemove(&list, 0);

							isFound = 1;

							break;
						}

						itNext(&it);
					}

					if (isFound)
						printf("Список был очищен, так как в нем было найдено введенное значение\n");
					else
						printf("Список не был очищен, так как в нем не найдено введенное значение\n");
				}

				break;
			}

			case 6: break;

			default:
			{
				printf("Ошибка. Такого пункта меню не существует\n");

				break;
			}
		}
	}
	while (action != 6);

	listDestroy(&list);

	return 0;
}
Ejemplo n.º 28
0
void hashTableInsert(hashTableType *table, handType *hand, unsigned long int response) {
	int index = handToIndex(hand);
	unsigned long long int key = handToKey(hand);
	table->heads[index] = listInsert(table->heads[index], key, response);
}
Ejemplo n.º 29
0
int main(int argc, char *argv[])
{
    List list;
    Data *data[6];

    int i, errors = 0;

    for (i = 0; i < 6; i++) {
        data[i] = calloc(1, sizeof(Data));
    }

    listInitialize(&list);

    TEST_INT(listLength(&list), 0);
    TEST_INT(listIsEmpty(&list),  TRUE);

    listAppendTail(&list, data[0]);
    listAppendTail(&list, data[1]);
    listAppendTail(&list, data[2]);
    listAppendTail(&list, data[3]);

    TEST_INT(listLength(&list), 4);
    TEST_INT(listIsEmpty(&list),  FALSE);

    TEST_PTR(listHead(&list), data[0]);
    TEST_PTR(listTail(&list), data[3]);

    TEST_PTR(listNext(data[0]), data[1]);
    TEST_PTR(listNext(data[1]), data[2]);
    TEST_PTR(listNext(data[2]), data[3]);
    TEST_PTR(listNext(data[3]), NULL);

    TEST_PTR(listPrev(data[3]), data[2]);
    TEST_PTR(listPrev(data[2]), data[1]);
    TEST_PTR(listPrev(data[1]), data[0]);
    TEST_PTR(listPrev(data[0]), NULL);

    TEST_PTR(listContaining(data[0]), &list);
    TEST_PTR(listContaining(data[1]), &list);
    TEST_PTR(listContaining(data[2]), &list);
    TEST_PTR(listContaining(data[3]), &list);

    listRemove(&list, data[0]);
    listRemove(&list, data[1]);
    listRemove(&list, data[2]);
    listRemove(&list, data[3]);

    TEST_INT(listLength(&list), 0);
    TEST_INT(listIsEmpty(&list),  TRUE);

    TEST_PTR(listContaining(data[0]), NULL);
    TEST_PTR(listContaining(data[1]), NULL);
    TEST_PTR(listContaining(data[2]), NULL);
    TEST_PTR(listContaining(data[3]), NULL);

    listInsertHead(&list, data[3]);
    listInsertHead(&list, data[2]);
    listInsertHead(&list, data[1]);
    listInsertHead(&list, data[0]);

    TEST_INT(listLength(&list), 4);
    TEST_INT(listIsEmpty(&list),  FALSE);

    TEST_PTR(listHead(&list), data[0]);
    TEST_PTR(listTail(&list), data[3]);

    TEST_PTR(listNext(data[0]), data[1]);
    TEST_PTR(listNext(data[1]), data[2]);
    TEST_PTR(listNext(data[2]), data[3]);
    TEST_PTR(listNext(data[3]), NULL);

    TEST_PTR(listPrev(data[3]), data[2]);
    TEST_PTR(listPrev(data[2]), data[1]);
    TEST_PTR(listPrev(data[1]), data[0]);
    TEST_PTR(listPrev(data[0]), NULL);

    TEST_PTR(listRemoveHead(&list), data[0]);
    TEST_PTR(listRemoveHead(&list), data[1]);
    TEST_PTR(listRemoveTail(&list), data[3]);
    TEST_PTR(listRemoveTail(&list), data[2]);

    TEST_INT(listLength(&list), 0);
    TEST_INT(listIsEmpty(&list),  TRUE);

    listAppendTail(&list, data[0]);
    listAppendTail(&list, data[3]);
    listAppend(&list, data[1], data[0]);
    listInsert(&list, data[2], data[3]);

    TEST_PTR(listRemoveHead(&list), data[0]);
    TEST_PTR(listRemoveHead(&list), data[1]);
    TEST_PTR(listRemoveTail(&list), data[3]);
    TEST_PTR(listRemoveTail(&list), data[2]);

    data[0]->i = 3;
    data[1]->i = 4;
    data[2]->i = 5;
    data[3]->i = 1;
    data[4]->i = 2;
    data[5]->i = 3;

    listAppendTail(&list, data[0]);
    listAppendTail(&list, data[1]);
    listAppendTail(&list, data[2]);
    listAppendTail(&list, data[3]);
    listAppendTail(&list, data[4]);
    listAppendTail(&list, data[5]);

    listSort(&list, cmp);

    TEST_PTR(listRemoveHead(&list), data[3]);
    TEST_PTR(listRemoveHead(&list), data[4]);
    TEST_PTR(listRemoveHead(&list), data[0]);
    TEST_PTR(listRemoveHead(&list), data[5]);
    TEST_PTR(listRemoveHead(&list), data[1]);
    TEST_PTR(listRemoveHead(&list), data[2]);

    exit(errors);
}
Ejemplo n.º 30
0
/*
 * internal declare-attribute.  This one allows colonized values for
 *  names, so that you can declare xmlns:-type attributes
 */
static genxAttribute declareAttribute(genxWriter w, genxNamespace ns,
				      constUtf8 name, constUtf8 valuestr,
				      genxStatus * statusP)
{
  int high, low;
  genxAttribute * aa = (genxAttribute *) w->attributes.pointers;
  genxAttribute a;

  w->arec.ns = ns;
  w->arec.name = (utf8) name;

  if (ns)
    w->arec.atype = ATTR_PREFIXED;
  else if (strncmp((const char *) name, "xmlns", STRLEN_XMLNS_COLON - 1) == 0)
    w->arec.atype = ATTR_NSDECL;
  else
    w->arec.atype = ATTR_NAKED;

  if (ns && (ns->defaultDecl == w->xmlnsEquals))
  {
    w->status = GENX_ATTRIBUTE_IN_DEFAULT_NAMESPACE;
    goto busted;
  }

  /* attribute list has to be kept sorted per c14n rules */
  high = w->attributes.count; low = -1;
  while (high - low > 1)
  {
    int probe = (high + low) / 2;
    if (orderAttributes(&w->arec, aa[probe]) < 0)
      high = probe;
    else
      low = probe;
  }

  /* if it was already there */
  if (low != -1 && orderAttributes(&w->arec, aa[low]) == 0)
    return aa[low];

  /* not there, build it */
  a = (genxAttribute) allocate(w, sizeof(struct genxAttribute_rec));
  if (a == NULL)
  {
    w->status = GENX_ALLOC_FAILED;
    goto busted;
  }

  a->writer = w;
  a->ns = ns;
  a->provided = False;
  a->atype = w->arec.atype;

  if ((a->name = copy(w, name)) == NULL)
  {
    w->status = GENX_ALLOC_FAILED;
    goto busted;
  }

  if ((w->status = initCollector(w, &a->value)) != GENX_SUCCESS)
    goto busted;

  if (valuestr)
    if ((w->status = collectString(w, &a->value, valuestr)) != GENX_SUCCESS)
      goto busted;
  
  w->status = listInsert(&w->attributes, a, high);
  if (w->status != GENX_SUCCESS)
    goto busted;
  
  *statusP = GENX_SUCCESS;
  return a;

busted:
  *statusP = w->status;
  return NULL;
}