Example #1
0
static void grow(Dict d)
{
    Dict d2;            /* new dictionary we'll create */
    struct dict swap;   /* temporary structure for brain transplant */
    int i;
    struct elt *e;

    d2 = internalDictCreate(d->size * GROWTH_FACTOR);

    for(i = 0; i < d->size; i++) {
        for(e = d->table[i]; e != 0; e = e->next) {
            /* note: this recopies everything */
            /* a more efficient implementation would
             * patch out the strdups inside DictInsert
             * to avoid this problem */
            DictInsert(d2, e->key, e->value, e->dist);
        }
    }

    /* the hideous part */
    /* We'll swap the guts of d and d2 */
    /* then call DictDestroy on d2 */
    swap = *d;
    *d = *d2;
    *d2 = swap;

    DictDestroy(d2);
}
Example #2
0
void join(int socket)
{
  char new_client_id[20];
  sprintf(new_client_id,"%d", client_id++);
  DictInsert(clients, new_client_id, -1);
  write(socket, new_client_id, sizeof(new_client_id));
}
Example #3
0
// прием соединения, если новых соединений нет или произошла ошибка то connectionfd == -1 
int acceptConnection(int epollfd, int socketfd, struct UserParams userParams){
  struct sockaddr addr;
  socklen_t addrlen = sizeof addr;

  int connectionfd = accept(socketfd, &addr, &addrlen);
  if (connectionfd == -1){
    perror ("failed to accept connection");
    return -1;
  }
  
  char host[NI_MAXHOST]; 
  char service[NI_MAXSERV]; 

  //резервирование символьного адреса и имени сервиса
  if(!getnameinfo(&addr, addrlen, host, sizeof host, service, sizeof service, NI_NUMERICHOST | NI_NUMERICSERV)){
  //вывод информации о полльзователе
    printf("new connection: %s:%s\n", host, service);
  }

  if (setNonBlock(connectionfd) == -1){
    fprintf(stderr, "failed to set socket %d nonblock", connectionfd);
    return -1;
  }
  //добавление в epol
  if (addToEpoll(epollfd, connectionfd) == -1){
    fprintf(stderr, "failed to add socket %d to epoll", connectionfd);
    return -1;
  }
  dprintf(connectionfd,"Enter login: "******"%d",connectionfd);
  DictInsert(userParams.login, conBuf, "");

  snprintf(conBuf, 4,"%d",connectionfd);
  DictInsert(userParams.fLogin, conBuf, "0");
  return 0;  
}
Example #4
0
/*
 * Install a handler for the object that has been given the name 'name'.
 * One handler is allowed per named object.
 * Return 0 on error, non-zero on success.
 */
DXLError
DXLSetObjectHandler(DXLConnection *conn, const char *varname,
			DXLObjectHandler handler, const void *data)
{
    HandlerData *hd;

    if (!conn->objectHandlerDict && !InitializeObjectHandler(conn)) 
	return ERROR;

    hd = NewHandlerData(handler,data); 
    if (!hd)
	return ERROR;

    if (!DictInsert(conn->objectHandlerDict,varname,hd, 
				DictDeleteHandlerData)) {
	DeleteHandlerData(hd);
 	return ERROR;
    }

    return OK;

}
Example #5
0
void get_next(char* client, int socket)
{
  int last_msg  = DictSearch( clients, client );
  int new_msg = last_msg + 1;
  char to_ret[MSG_SIZE];
  printf(" Client: %s Last_Msg: %d New_Msg: %d \n", client, last_msg, new_msg);
  if( msg_in_history(client, last_msg) == 0 ) 
  {
    if( new_msg < num_msg)
    {
      sprintf(to_ret,"%s", DictSearchS(messages, new_msg)); 
      DictDelete(clients, client);
      DictInsert(clients, client, new_msg);
    }
    else
    {
      sprintf(to_ret,"%s","No new messages ");
    }
  }

  write(socket, to_ret, sizeof(to_ret)); 
}//end get_next
Example #6
0
int
main(int argc, char* argv[])
{
    Dict d;
    int i;
    char a = 96;
    //int code = 0;
    int MAXBITS = 12;
    int pused = 2;
    int pref = 0;
    if (argc == 2){
        MAXBITS = atoi(argv[1]);
    }
    d = internalDictCreate(1 << MAXBITS);

    printf("%d", d->size);

    for(i = 0; i < 8; i++) {
        a++;
        pref =(int) a + i;
        if(d->n >= d->size) {
            printf("%s\n", "Table filled, grow");
            //exit(1);
            Dictgrow(d);
        }       
        DictInsert(d, pref, a, i);
        DictUse(d, pref, a, i);
        if (i % 2 == 0){
            DictUse(d, pref, a, i);
        }
        printf("Found (%d, %d) at code %d\n", pref, a, i);

    }
    DictPrune(d, pused);
    DictInsert(d, 105, 'e', 4);
    FILE *fp = fopen("table", "w");
    DicttoFile(d, fp);

    /*printf("%d", d->size);

    for(i = 0; i < 26; i++) {
        a++;
        code = (int) a + i;
        if(d->n >= d->size) {
            printf("%s\n", "Table filled, grow by x2");
            Dictgrow(d);
        }
        DictInsert(d, i, (int) a, code);
        printf("Found (%d, %d) with code %d\n", i, a, DictSearch(d, i, a));
    }
    FILE *fp = fopen("table", "w");
    DicttoFile(d, fp);
    DictDelete(d, 7, 104);
    assert(DictSearch(d, 7, 104) == -1);
    a=96;
    for(i = 0; i < 26; i++) {
        a++;
        if (DictSearch(d, i, (int)a) != -1){
            printf("Found (%d, %d) with code %d\n", i, a, DictSearch(d, i, a));
        }
        else{
            printf("Did not find (%d, %d)\n", i, a);
        }
    }*/

    DictDestroy(d);
    printf("%s\n", "Dictionary is empty");

    return 0;
}
Example #7
0
//чтение данных, присланных пользователем
int handlerRequest(int epollfd, int connectionfd, struct UserParams userParams, pthread_mutex_t mutex){
  int buffCount = 1024;
  int i = 3;
  char *buffer = (char*) malloc(buffCount * sizeof(char));
  char conBuf[4];
  ssize_t count = read(connectionfd, buffer, sizeof buffer);
  char *ret;
  //динамическое выделение памяти для буфера
  char bufferN[buffCount];
  ssize_t countN = read(connectionfd, bufferN, sizeof bufferN);
  while(countN > 0){
    ret = (char*)realloc(buffer,i*buffCount*sizeof(char));
    if(!ret){
      perror("realloc");
      exit(1);
    }
    strcat(buffer, bufferN);
    count+=countN;
    i++;
    countN = read(connectionfd, bufferN, sizeof bufferN);
  }
  switch(count){
    case -1:
      if (errno != EAGAIN)
        perror ("failed to read data");
      break;
    case 0:
      printf("client closed the connection");
      break;
    default:
      snprintf(conBuf, 4,"%d",connectionfd);
      //ввод логина
      if(!strcmp(DictSearch(userParams.login, conBuf),"")){
        if (count > 1){
          char *tmpLogin = (char*) malloc(count+1);
          strncpy(tmpLogin, buffer, count);
          tmpLogin[count] = '\0';
          DictInsert(userParams.login,conBuf,tmpLogin);

          printf("%s\n", DictSearch(userParams.login, conBuf));
          dprintf(connectionfd, "Enter password: "******"Enter login: "******"0")){
          char *tmpPass=(char*) malloc(count+1); 
          strncpy(tmpPass, buffer, count);
          tmpPass[count] = '\0';
          //вызов проверки
          pthread_mutex_lock(&mutex);
          int check = checkLogin(DictSearch(userParams.login, conBuf), tmpPass);
          pthread_mutex_unlock(&mutex);
          if(check == 1){
            DictDelete(userParams.fLogin,conBuf);
            DictInsert(userParams.fLogin,conBuf,"1");
            DictInsert(userParams.location,conBuf,"cd user_root/;");
            dprintf(connectionfd, "!!Enter command: ");
          }
          else{
            DictDelete(userParams.login,conBuf);
            DictInsert(userParams.login,conBuf,"");
            dprintf(connectionfd,"Enter login: "******"logout",6))
            close(connectionfd);
          else{
          int c;
          FILE *pp;
          extern FILE *popen();
          char* tempCd = (char*) malloc(1024*sizeof(char));
          strcpy(tempCd, DictSearch(userParams.location, conBuf));
          //strcat(tempCd, ";");
          printf("----->%s\n",tempCd);
          if ( !(pp=popen(strcat(tempCd, buffer), "r")) ){
             free(tempCd);
            return 1;
          }
          
          while ( (c=fgetc(pp)) != EOF ) {
          putc(c, stdout); 
          dprintf(connectionfd,"%c",c);
          fflush(pp);
          }   
          pclose(pp);
          free(tempCd);
          printf("%d user command: %.*s", connectionfd, count, buffer); 
          dprintf(connectionfd, "Enter command: ");
        }
        }
      }
  }
  free(buffer);
}
Example #8
0
int search(struct position source, struct position target, int (*blocked)(struct position))
{
    struct position current;
    current = source;

    Dict d;
    d = DictCreate();

    PQ* q;
    q = initQueue();

    heapNode hn;
    hn.distFromSource = 0;
    hn.value = abs(current.x - target.x) + abs(current.y - target.y);
    hn.pos = current;
    enqueue(hn,q);
    DictInsert(d,current.x,current.y,hn.distFromSource);

    while(q->size)	//stops when priority queue is empty
    {
        int i;
        hn = dequeue(q);
        current = hn.pos;
        if(foundTarget(current,target))	//hooray! target found!!
        {
            DictDestroy(d);
            destroyQueue(q);
            return hn.distFromSource;
        }
        for(i = 0; i < 4; i++) //for loop explores all the four neighbors defined as 0...3
        {
            struct position neighbor = createNeighbor(current,i);
            int dictSearchDist = DictSearch(d,neighbor.x,neighbor.y);
            if(!blocked(neighbor) && dictSearchDist < 0)	//add the neighbor to PQ
            {
                DictInsert(d,neighbor.x,neighbor.y,hn.distFromSource + 1);
                heapNode node;
                int distToTarget = abs(neighbor.x - target.x) + abs(neighbor.y - target.y);	//manhattan distance
                node.value = (hn.distFromSource + 1) + distToTarget;
                node.pos = neighbor;
                node.distFromSource = hn.distFromSource + 1;
                enqueue(node,q);
            }
            else if(dictSearchDist >= 0)
            {
                if(dictSearchDist > hn.distFromSource + 1)
                {
                    DictInsert(d,neighbor.x,neighbor.y,hn.distFromSource + 1);
                    heapNode node;
                    int distToTarget = abs(neighbor.x - target.x) + abs(neighbor.y - target.y);	//manhattan distance
                    node.value = (hn.distFromSource + 1) + distToTarget;
                    node.pos = neighbor;
                    node.distFromSource = hn.distFromSource + 1;
                    enqueue(node,q);
                }
            }
        }
    }
    DictDestroy(d);
    destroyQueue(q);
    return NO_PATH;
}