/*------------------------------------------------------------------ * *------------------------------------------------------------------*/ int main(void) { Hash *iHash; int i; int counter; iHash = HashCreate(sizeof(int),3,compareFunc,hashFunc,NULL); for (i= 1; i<10; i++) HashAdd(iHash,&i); for (i=20; i>10; i--) HashAdd(iHash,&i); for (i=0; i<=21; i++) if (!HashFind(iHash,&i)) printf("didn't find %d\n",i); counter = 1; HashIterate(iHash,iterateFunc,&counter); for (i=-1; i<5; i++) HashDelete(iHash,&i); for (i=21; i>15; i--) HashDelete(iHash,&i); counter = 1; HashIterate(iHash,iterateFunc,&counter); HashDestroy(iHash); return 0; }
local int arenas_get_names(DBT *key, DBT *val) { arenas_info *i; if (key->size == sizeof(struct player_record_key)) { struct player_record_key *k = key->data; if (!(i = HashGetOne(arenas_hash, k->arenagrp))) HashAdd(arenas_hash, k->arenagrp, i = amalloc(sizeof(*i))); i->precs++; i->pbytes += key->size + val->size; } else if (key->size == sizeof(struct arena_record_key)) { struct arena_record_key *k = key->data; if (!(i = HashGetOne(arenas_hash, k->arena))) HashAdd(arenas_hash, k->arena, i = amalloc(sizeof(*i))); i->arecs++; i->abytes += key->size + val->size; } else if (key->size == sizeof(struct current_serial_record_key)) { struct current_serial_record_key *k = key->data; if (!(i = HashGetOne(arenas_hash, k->arenagrp))) HashAdd(arenas_hash, k->arenagrp, i = amalloc(sizeof(*i))); i->srecs++; i->sbytes += key->size + val->size; } else printf("unknown key type: length %d bytes\n", key->size); return FALSE; }
void Y_set_vars(int nArgs) { Symbol *stack = sp - nArgs + 1; IOStream *file, *child; char **vars, **rvars; long i, nvars, nrvars; Dimension *dims; if (nArgs<2 || nArgs>3 || !stack[0].ops || !stack[1].ops) YError("set_vars takes exactly two or three arguments"); file = YGetFile(stack++); child = file->history? file->history->child : 0; vars = YGet_Q(stack++, 1, &dims); nvars = (vars&&dims)? (dims->next? -1 : dims->number) : 0; if (nArgs==3) { rvars = YGet_Q(stack++, 1, &dims); nrvars = (vars&&dims)? (dims->next? -1 : dims->number) : 0; } else { rvars = 0; nrvars = 0; } if (nvars<0 || nrvars<0) YError("set_vars var lists must be 1D"); if ((nvars && nvars!=file->dataTable.nItems) || (nrvars && nrvars!=(child? child->dataTable.nItems : 0))) YError("set_vars var lists must match number of vars in file"); if (nvars) { HashTable tmp; y_hashtmp *h = y_new_tmpobj(sizeof(y_hashtmp), y_zap_hashtmp); HashInit(&h->table, nvars); PushDataBlock(h); for (i=0 ; i<nvars ; i++) if (HashAdd(&h->table, vars[i], 0)) break; if (i<nvars) YError("duplicate names in set_vars static var list"); if (p_signalling) p_abort(); tmp = h->table; h->table = file->dataTable; file->dataTable = tmp; Drop(1); } if (nrvars) { HashTable tmp; y_hashtmp *h = y_new_tmpobj(sizeof(y_hashtmp), y_zap_hashtmp); HashInit(&h->table, nvars); PushDataBlock(h); for (i=0 ; i<nrvars ; i++) if (HashAdd(&h->table, rvars[i], 0)) break; if (i<nrvars) YError("duplicate names in set_vars record var list"); if (p_signalling) p_abort(); tmp = h->table; h->table = child->dataTable; child->dataTable = tmp; Drop(1); } }
void YpQuine(char *name, int nQuined) { if (!HashAdd(&quineTable, name, 0L)) { HASH_MANAGE(quineTable, int, nQuinedArgs); } nQuinedArgs[hashIndex]= nQuined; }
Literal YpName(char *name, long len) { if (!HashAdd(&literalTable, name, len)) { /* this name has never been seen before */ HASH_MANAGE(literalTable, long, literalTypes); literalTypes[hashIndex]= 0; } return hashIndex; }
int main() { static const char * keyList[] = {"red","orange","yellow","green", "blue", "violet" }; static int valuList[] = {1,43,640, 747, 42, 42}; int ix; for (ix=0; ix<6; ix++) { HashAdd(keyList[ix], valuList[ix]); } return 0; }
local int players_get_names(DBT *key, DBT *val) { players_info *i; if (key->size == sizeof(struct player_record_key)) { struct player_record_key *k = key->data; if (!(i = HashGetOne(players_hash, k->name))) HashAdd(players_hash, k->name, i = amalloc(sizeof(*i))); i->recs++; i->bytes += key->size + val->size; } return FALSE; }
asmlinkage long ManageMailbox(bool stop, int *count){ struct Mailbox* self; struct list* hashLink; spin_lock_irq(&creationLock); if ((self = HashFind(current->tgid)) == NULL){ //Allocate and initialize the mailbox for the receiver printk(KERN_INFO "Mailbox created via mng for %d \n", current->tgid); self = kmem_cache_alloc(mailboxCache, GFP_KERNEL); self->owner = current->tgid; self->numberofMessages = 0; self->status = false; self->message = NULL; atomic_set(&self->references, 0); self->waitingFull = 0; self->waitingEmpty = 0; init_waitqueue_head(&self->canExit); spin_lock_init(&self->lock); init_waitqueue_head(&self->notEmpty); init_waitqueue_head(&self->notFull); //Allocate and initialize the hash link for the //receiver hashLink = kmem_cache_alloc(listCache, GFP_KERNEL); hashLink->mailbox = self; hashLink->pid = current->tgid; hashLink->next = NULL; HashAdd(current->tgid, hashLink); } atomic_add(1, &self->references); spin_unlock_irq(&creationLock); spin_lock_irq(&self->lock); // If the count pointer isn't null, copy the number of messages to user space if (count != NULL){ if(copy_to_user(count, &self->numberofMessages, sizeof(int))){ atomic_sub(1, &self->references); wake_up_all(&self->canExit); spin_unlock_irq(&self->lock); return MSG_ARG_ERROR; } } // If stop is set to true, need to wake up all the waiting processes so that they can return if (stop == true){ self->status = stop; wake_up_all(&self->notFull); wake_up_all(&self->notEmpty); } atomic_sub(1, &self->references); wake_up_all(&self->canExit); spin_unlock_irq(&self->lock); return 0; }
CHashWS *WSHashAdd(U8 *w) { CHashWS *tempw=HashFind(w,ws_hash_table,HTT_WORD); if (tempw) { tempw->hits++; return tempw; } tempw=ACAlloc(sizeof(CHashWS)); tempw->str=AStrNew(w); tempw->type=HTT_WORD; tempw->use_cnt=1; tempw->hits=1; tempw->num=-1; HashAdd(tempw,ws_hash_table); ws_num_words++; return tempw; }
local void player_action(Player *p, int action, Arena *arena) { PData *pdata = PPDATA(p, pdata_key); if (action == PA_CONNECT) { FormulaVariable *var = amalloc(sizeof(FormulaVariable)); var->name = astrdup("me"); var->type = VAR_TYPE_PLAYER; var->p = p; pdata->vars = HashAlloc(); HashAdd(pdata->vars, var->name, var); } else if (action == PA_DISCONNECT) { HashEnum(pdata->vars, var_free_enum, NULL); HashFree(pdata->vars); } }
THash *ap_set_diaglevel(const char *category, int level) { THash *dl = 0; pthread_mutex_lock(&diag_levels_mutex); if (!diag_levels) { return( 0 ); } dl = HashFind(diag_levels, (char *)category); if (dl) { dl->t_val = (void*)level; } else { dl = HashAdd(diag_levels, (char *)category, (void*)level); } pthread_mutex_unlock(&diag_levels_mutex); return dl; }
/* Record the given globTab index in the sourceList. This index corresponds to either a func definition, a struct definition, or an extern statement outside of any functions. */ long RecordSource(long index) { long isrc = -1; if (nYpIncludes) { long *list, len; if (HashAdd(&sourceTab, ypIncludes[nYpIncludes-1].filename, 0L)) { list = sourceList[hashIndex]; len = lenSourceList[hashIndex]; } else { HASH_MANAGE(sourceTab, long *, sourceList); HASH_MANAGE(sourceTab, long, lenSourceList); sourceList[hashIndex] = list = 0; lenSourceList[hashIndex] = len = 0; } if (!(len&7)) sourceList[hashIndex] = list = p_realloc(list, sizeof(long)*(len+8)); list[len++] = index; lenSourceList[hashIndex] = len; isrc = hashIndex; } return isrc; }
//============================================================== sParam *ObjSetup(char *id_str) //-------------------------------------------------------------- // オブジェクトのセットアップ // ※同じ名前が存在する場合、読み込み直す //-------------------------------------------------------------- // in: id_str = 識別子 //-------------------------------------------------------------- // out: 読み込んだパラメータ //============================================================== { char file[FNAME_MAXLEN]; sParam *param; param = (sParam *)HashGet(param_hash, id_str); if(param) ParamDestroy(param); sprintf(file, OBJ_FILE_PATH"/%s.param", id_str); param = ParamRead(file); HashAdd(param_hash, id_str, param); return param; }
asmlinkage long SendMsg(pid_t dest, void* msg, int len, bool block){ struct Mailbox* receiver; struct list* hashLink; struct Message* sendingMessage; struct Message* messages; int pidstatus; spin_lock_irq(&creationLock); pidstatus = verifyPID(dest); if(pidstatus == PIDDNE){ spin_unlock_irq(&creationLock); return MAILBOX_INVALID; } else if(pidstatus == KERNPID){ if(HashFind(dest) == NULL){ hashLink = kmem_cache_alloc(listCache, GFP_KERNEL); hashLink->mailbox = NULL; hashLink->next = NULL; HashAdd(dest, hashLink); } spin_unlock_irq(&creationLock); return MAILBOX_INVALID; } if ((receiver = HashFind(dest)) == NULL){ //Allocate and initialize the mailbox for the receiver printk(KERN_INFO "Mailbox created via send for %d \n", dest); receiver = kmem_cache_alloc(mailboxCache, GFP_KERNEL); receiver->owner = dest; receiver->numberofMessages = 0; receiver->status = false; receiver->message = NULL; atomic_set(&receiver->references, 0); receiver->waitingFull = 0; receiver->waitingEmpty = 0; init_waitqueue_head(&receiver->canExit); spin_lock_init(&receiver->lock); init_waitqueue_head(&receiver->notEmpty); init_waitqueue_head(&receiver->notFull); //Allocate and initialize the hash link for the receiver hashLink = kmem_cache_alloc(listCache, GFP_KERNEL); hashLink->mailbox = receiver; hashLink->pid = dest; hashLink->next = NULL; HashAdd(dest, hashLink); } if (atomic_read(&receiver->references) == -1){ spin_unlock_irq(&creationLock); return MAILBOX_ERROR; } atomic_add(1, &receiver->references); spin_unlock_irq(&creationLock); spin_lock_irq(&receiver->lock); //If the message length is greater than the max or less than zero, it returns the message length error if (len > MAX_MSG_SIZE || len < 0){ atomic_sub(1, &receiver->references); wake_up_all(&receiver->canExit); spin_unlock_irq(&receiver->lock); return MSG_LENGTH_ERROR; } //If the receiver's mailbox is stopped, it will return an error if (receiver->status == true){ atomic_sub(1, &receiver->references); wake_up_all(&receiver->canExit); spin_unlock_irq(&receiver->lock); return MAILBOX_STOPPED; } spin_unlock_irq(&receiver->lock); //Allocates and initializes the message to be sent sendingMessage = kmem_cache_alloc(messageCache, GFP_KERNEL); sendingMessage->sender = current->tgid; sendingMessage->length = len; sendingMessage->msg = kmem_cache_alloc(contentCache, GFP_KERNEL); copy_from_user(sendingMessage->msg, msg, len); sendingMessage->next = NULL; spin_lock_irq(&receiver->lock); // Mailbox is full, and block is set to false, need to return an error if (receiver->numberofMessages == 32 && block == false){ atomic_sub(1, &receiver->references); wake_up_all(&receiver->canExit); spin_unlock_irq(&receiver->lock); return MAILBOX_FULL; } // Mailbox is full, and block is true, so it needs to wait on the queue else if (receiver->numberofMessages == 32 && block == true){ receiver->waitingFull++; spin_unlock_irq(&receiver->lock); wait_event(receiver->notFull, (receiver->numberofMessages < 32 || receiver->status == true)); spin_lock_irq(&receiver->lock); receiver->waitingFull--; if (receiver->waitingFull == 0){ wake_up_all(&receiver->canExit); } if (receiver->status == true){ atomic_sub(1, &receiver->references); wake_up_all(&receiver->canExit); spin_unlock_irq(&receiver->lock); return MAILBOX_STOPPED; } } messages = receiver->message; // If the mailbox is empty, the current message being sent becomes the head of the receivers message list if (messages == NULL){ receiver->message = sendingMessage; receiver->numberofMessages++; wake_up_all(&receiver->notEmpty); atomic_sub(1, &receiver->references); wake_up_all(&receiver->canExit); spin_unlock_irq(&receiver->lock); return 0; } // The message is put onto the end of the receiver's list of messages while(messages->next != NULL){ messages = messages->next; } messages->next = sendingMessage; receiver->numberofMessages++; atomic_sub(1, &receiver->references); wake_up_all(&receiver->canExit); spin_unlock_irq(&receiver->lock); return 0; }
/* * Adds a listener. * First it finds the listenerList from the hash table (or creates * a new if not found) with source and eventType as keys. * Then a entry is insterted into the list with handlerFunc and * handlerData as keys */ void em_addListener( void *source, EventType eventType, EventHandlerFunc handlerFunc, void *handlerData, Boolean makeNewThread ) { int i; int res; /* The soon enough found listenerlist */ ListenerList listenerList = NULL; /* The template of how to find the listenerList */ sListenerList findTemplate = {source, eventType, {{0}}, {NULL} }; DEBUG(" enter ( source %p, type %d, handlerData %p, handlerFunc %p, makeNewThread %d )\n", source, eventType, handlerData, handlerFunc, makeNewThread ); threading_mutex_lock( &(listenersHashTableLock) ); /* Get listener list from hash table with keys (source, eventType) */ listenerList = HashFind(listenersHashTable, &findTemplate); /* Check if we got a listenerList or if we got null */ if (listenerList == NULL) { DEBUG("create new listenersList for {source %p, type %d}\n", source, eventType); /* If null then create a new listenerList, initialize * it and add it to the Hashtable */ listenerList = malloc(sizeof(sListenerList)); listenerList->source = source; listenerList->eventType = eventType; threading_mutex_init( &(listenerList->listenerListLock) ); /* error = sem_init( &(listenerList->listenerListLock), 0, 1 ); assert( error == 0 ); */ for (i = 0; i < LLIST_NO_ELEMS; i++) listenerList->listenerEntryList[i] = NULL; res = HashAdd(listenersHashTable, listenerList); /* Check if success */ assert(res != 0); } threading_mutex_unlock( &(listenersHashTableLock) ); /* Now we got a listenerList. First lock it. * Then loop through the list to check for an empty entry */ DEBUG(" get lock %p->listenerListLock \n", listenerList ); threading_mutex_lock( &(listenerList->listenerListLock) ); DEBUG(" got lock %p->listenerListLock \n", listenerList ); for (i=0; i < LLIST_NO_ELEMS; i++) { if (listenerList->listenerEntryList[i] == NULL) { /* Add it here */ listenerList->listenerEntryList[i] = (ListenerEntry) malloc(sizeof(sListenerEntry)); listenerList->listenerEntryList[i]->handlerFunc = handlerFunc; listenerList->listenerEntryList[i]->handlerData = handlerData; listenerList->listenerEntryList[i]->makeNewThread = makeNewThread; break; } } /* Unlock list */ threading_mutex_unlock( &(listenerList->listenerListLock) ); DEBUG(" released lock %p->listenerListLock \n", listenerList ); /* sem_post(&(listenerList->listenerListLock)); */ /* Error if no free entrys in list */ assert (i < LLIST_NO_ELEMS); #ifndef NDEBUG if( debug ) { fprintf( stderr, "Added listener "); writeListenerList(listenerList); } #endif /* NDEBUG */ DEBUG("leave\n"); }
int handle_http_propfind(http_req * req, http_rsp * rsp) { int ret = OK; HashElement * e = NULL; int depth = -1; HashHandle props = NULL_HANDLE; CacheHandle cache = NULL_HANDLE; char * propxml = NULL; int contentlen = 0; char * vpath = req->uri; struct stat buf; WEBLOG_API(); #ifdef WEBCFG_SUPPORT_AUTH /* Authentication has a very high priority. */ if (OK != CheckAuthorization(req, rsp)) { return handle_http_error(401, req, rsp); } #endif if(OK != Webdav_CheckPath(req->uri)) { WEBLOG_ERROR("<%s> PROPFIND is not allowed for non-webdav path [%s].\n", __FUNCTION__, req->uri); handle_http_error(403, req, rsp); ret = NG; goto __error_out; } if(0 == strlen(vpath)) { strcat(vpath, "/"); WEBLOG_VERBOSE("<%s> redirect to root path. [%s].\n", __FUNCTION__, vpath); } WEBLOG_INFO("<%s> stat the file \"%s\".\n", __FUNCTION__, vpath); ret = stat(vpath, &buf); /* Check if statistics are valid: */ if(ret != 0) { WEBLOG_ERROR("<%s> fail to stat the file \"%s\".\n", __FUNCTION__, vpath); switch (errno) { case ENOENT: WEBLOG_ERROR("<%s> File %s not found.\n", __FUNCTION__, vpath); handle_http_error(404, req, rsp); ret = NG; goto __error_out; case EINVAL: /* no break */ default: /* Should never be reached. */ WEBLOG_ERROR("<%s> Unexpected error in _stat.\n", __FUNCTION__); handle_http_error(500, req, rsp); ret = NG; goto __error_out; } } props = HashTableCreate(64); ASSERT(props != NULL_HANDLE); /* get depth. */ e = HashLookup(req->headOptions, "Depth"); if(!e) depth = -1; else if(e->value.data.string[0] == '0') depth = 0; else if(e->value.data.string[0] == '1') depth = 1; else depth = -1; if(depth == -1 && TRUE == Webdav_isFolder(vpath)) { WEBLOG_ERROR("<%s> PROPFIND a collection with infinite depth is not allowed.\n", __FUNCTION__); handle_http_error(403, req, rsp); ret = NG; goto __error_out; } #ifdef WEBCFG_MINIMIZE_SERVER #else e = HashLookup(req->headOptions, "Content-Type"); if(e && strstr(e->value.data.string, "xml")) { char * xmlsockbuf = NULL; char strbuf[128] = {0}; char *end, *p, *q; HashValue eeee = HashString("", FALSE); // empty value! WEBLOG_INFO("<%s> Client request props in a xml body.\n", __FUNCTION__); e = HashLookup(req->headOptions, "Content-Length"); if(!e) { /* RFC2616, 14.23. */ WEBLOG_ERROR("<%s> Missing \"Content-Length\" for xml body.\n", __FUNCTION__); handle_http_error(400, req, rsp); ret = NG; goto __error_out; } contentlen = atoi(e->value.data.string); xmlsockbuf = (char *)webmalloc(contentlen+1); memset(xmlsockbuf, 0, contentlen+1); if(req->datalen > 0) // data left in head buffer. { memcpy(xmlsockbuf, req->sockbuf, req->datalen); WEBLOG_VERBOSE("<%s> previous buffered %d/%d bytes consumed.\n", __FUNCTION__, req->datalen, contentlen); } /* if there's more data in socket.... */ if (req->datalen < contentlen) { /* read rest of data from socket. */ p = xmlsockbuf + req->datalen; req->datalen = recv(req->sock, p, contentlen-req->datalen, 0); WEBLOG_VERBOSE("<%s> %d/%d bytes read from socket.\n", __FUNCTION__, req->datalen, contentlen); dumpText(xmlsockbuf, contentlen); } p = strstr(xmlsockbuf, "<prop>") + 6; end = strstr(xmlsockbuf, "</prop>"); if(strstr(xmlsockbuf, "<allprop/>")) { WEBLOG_INFO("<%s> client request all props.\n", __FUNCTION__); } else { ASSERT(p<end); *end = '\0'; /* good for str api. */ /* Possible Value: WinXP: <propname/> Cadaver: <propname xmlns="DAV:"/> */ do { p = strchr(p, '<'); if(!p) break; else p++; q = strstr(p, "/>"); ASSERT(q && (q-p < sizeof(strbuf))); strncpy(strbuf, p, q-p); p = strchr(strbuf, ' '); if(p) *p = '\0'; p = strtrim(strbuf); WEBLOG_INFO("<%s> client request prop: <%s>\n", __FUNCTION__, p); HashAdd(props, p, eeee); p = q + 2; } while(p<end); /* <xxx/>\r\n</prop> */ } } #endif cache = CacheCreate(); Webdav_Props(props, cache, vpath, depth); contentlen = CacheGetData(cache, &propxml); ASSERT(propxml); dumpText(propxml, contentlen); WEBLOG_INFO("<%s> response xml ready. len %d.\n", __FUNCTION__, contentlen); rsp->code = 207; rsp->body = propxml; http_add_rspoption(rsp, "Content-Type", "text/xml"); http_send_response(rsp); __error_out: if (props != NULL_HANDLE) HashTableDestroy(props); if (cache != NULL_HANDLE) CacheDestroy(cache); return ret; }
void http_add_rspoption(http_rsp * rsp, char * name, char * value) { HashValue v = HashString(value, TRUE); HashAdd(rsp->headOptions, name, v); }
/*------------------------------------------------------------------ * add default key words to reserved hash *------------------------------------------------------------------*/ void InitializeReservedHash( Info *info, char *keyList ) { int i; char *part; /*--------------------------------------------------------------- * create hash table *---------------------------------------------------------------*/ info->reservedHash = HashCreate(sizeof(char *), 30, (HashFunc *)IdentHash, (ListCompareFunc *)IdentCompare, cPostNoMem); if (!info->reservedHash) cPostError(1,"error creating reserved word hash table"); for (i=0; i<sizeof(ReservedTokens)/sizeof(char *); i++) if (!HashAdd(info->reservedHash,&(ReservedTokens[i]))) cPostError(1,"error adding reserved word '%s' to hash table", ReservedTokens[i]); /*--------------------------------------------------------------- * loop through the comma separated keys ... *---------------------------------------------------------------*/ part = strtok(keyList,","); while (part) { /*------------------------------------------------------------ * special c++ token *------------------------------------------------------------*/ if (!Stricmp("c++",part)) { for (i=0; i<sizeof(CppReservedTokens)/sizeof(char *); i++) if (!HashAdd(info->reservedHash,&(CppReservedTokens[i]))) cPostError(1,"error adding reserved word '%s' to hash table", CppReservedTokens[i]); } /*------------------------------------------------------------ * use Java tokens *------------------------------------------------------------*/ if (!Stricmp("java",part)) { /*------------------------------------------------------------ * remove default C tokens *------------------------------------------------------------*/ for (i=0; i<sizeof(ReservedTokens)/sizeof(char *); i++) HashDelete(info->reservedHash,&(ReservedTokens[i])); /*------------------------------------------------------------ * add Java tokens *------------------------------------------------------------*/ for (i=0; i<sizeof(JavaReservedTokens)/sizeof(char *); i++) if (!HashAdd(info->reservedHash,&(JavaReservedTokens[i]))) cPostError(1,"error adding reserved word '%s' to hash table", JavaReservedTokens[i]); } /*------------------------------------------------------------ * file name *------------------------------------------------------------*/ else if (('@' == part[0]) && (1 != strlen(part))) { TokFileInfo tfi; char *key; part++; tfi = TokFileOpen(part); if (!tfi) cPostError(0,"error opening file '%s' for reading",part); else { while (NULL != (part = TokFileNext(tfi))) { key = malloc(1 + strlen(part)); if (!key) cPostError(1,"out of memory!!"); strcpy(key,part); if (!HashAdd(info->reservedHash,&key)) cPostError(0,"error adding reserved word '%s' to hash table; word ignored", key); } } } /*------------------------------------------------------------ * plain old token *------------------------------------------------------------*/ else if (!HashAdd(info->reservedHash,&part)) { cPostError(0,"error adding reserved word '%s' to hash table; word ignored",part); } part = strtok(NULL,","); } }
int main(void) { int size = 0, h; char cmd, key[1024], value[1024], buf[1024]; Hash *hash; // ハッシュテーブルの生成 printf("ハッシュテーブルの大きさを入力して下さい: "); scanf("%d", &size); if (size < 1) return -1;// 入力数エラー hash = HashAlloc(size); if (hash == NULL) return -1; // メモリ確保失敗 puts("* ハッシュテーブルを操作するコマンドを入力して下さい."); puts("* データを格納:a"); puts("* キーを削除:x"); puts("* キーに対応するデータの取得:g"); puts("* ハッシュテーブルを表示:d"); puts("* ハッシュ値の表示:h"); puts("* ハッシュテーブルをクリア:c"); puts("* 終了:q"); do { printf(": "); scanf("%s", buf); cmd = buf[0]; switch (cmd) { case 'a': /* データを格納 */ printf("名前を入力して下さい:"); scanf("%s", key); printf("血液型を入力して下さい:"); scanf("%s", value); if (HashAdd(hash, key, value) == TRUE) { // hash, name, blood-type printf("%s=%sを格納しました.\n", key, value); } else { /* 衝突 */ printf("既に同じキーを持つデータが存在します.\n"); } break; case 'd': /* データを表示 */ HashDump(hash); break; case 'c': /* ハッシュテーブルをクリア */ HashClear(hash); break; case 'x': /* キーを削除 */ printf("誰を削除しますか?:"); scanf("%s", key); if(HashDelete(hash, key) == TRUE) { printf("%sを削除しました.\n", key); } else { printf("%sは登録されていません.\n", key); } break; case 'g': /* キーに対応するデータを取得 */ printf("名前を入力して下さい:"); scanf("%s", key); if (HashGet(hash, key, value) == TRUE) { printf("%sの血液型は%sです.\n", key, value); } else { printf("%sは登録されていません.\n", key); } break; case 'h': /* キーに対応するデータを取得 */ printf("名前を入力して下さい:"); scanf("%s", key); h = HashCode(hash, key); printf("%sのハッシュ値は%dです.", key, h); break; case 'q': /* 終了 */ puts("プログラムを終了します."); break; case '\n': /* 改行 */ case '\r': /* 復帰 */ break; default: /* 入力エラー */ puts("コマンドが正しくありません."); break; } } while (cmd != 'q'); HashDump(hash); // 解放前の出力 HashFree(hash); // メモリ解放 return 0; }
static int _GetObjectProps(HashHandle hash, CacheHandle cache, char * webpath) { int ret = 0; char localpath[128] = {0}; char strbuf[128] = {0}; HashElement * e = NULL; int directory = FALSE; struct stat filestt; char last_modify_time[100] = {0}; getlocalpath(webpath, localpath); WEBLOG_INFO("<%s> [w]%s, [l]%s.\n", __FUNCTION__, webpath, localpath); ret = stat(localpath, &filestt); if(ret != 0) { switch (errno) { case ENOENT: WEBLOG_INFO("<%s> File %s not found.\n", __FUNCTION__, localpath); return WEBDAVR_NOT_FOUND; case EINVAL: default: WEBLOG_INFO("<%s> Unexpected error in _stat.\n", __FUNCTION__); return WEBDAVR_NG; } } directory = (S_IFDIR & filestt.st_mode); WEBLOG_INFO("<%s> %s is a %s.\n", __FUNCTION__, localpath, directory?"folder":"file"); if(directory) { HashAdd(hash, "resourcetype", HashString("<D:collection/>", TRUE)); HashAdd(hash, "getcontenttype", HashString("httpd/unix-directory", TRUE)); HashAdd(hash, "getcontentlength", HashString("", TRUE)); } else { //HashAdd(hash, "resourcetype", HashString("", TRUE)); // empty this HashAdd(hash, "getcontenttype", HashString("application/octet-stream", TRUE)); sprintf(strbuf, "%ld", filestt.st_size); WEBLOG_INFO("<%s> File size : %ld\n", __FUNCTION__, filestt.st_size ); HashAdd(hash, "getcontentlength", HashString(strbuf, TRUE)); } WEBLOG_INFO("<%s> Time modified : %s", __FUNCTION__, ctime(&filestt.st_mtime)); //HashAdd(hash, "getlastmodified", HashString(ctime(&filestt.st_mtime), TRUE)); //HashAdd(hash, "getlastmodified", HashString("Thu, 28 Mar 2013 06:30:48 GMT", TRUE)); strftime( last_modify_time, sizeof(last_modify_time), "%a, %d %b %Y %H:%M:%S GMT", gmtime(&filestt.st_mtime)); HashAdd(hash, "getlastmodified", HashString(last_modify_time, TRUE)); CacheWriteString(cache, "\t<D:response>\n" "\t\t<D:href>"); CacheWriteString(cache, "/webdav"); memset(strbuf, 0, sizeof(strbuf)); url_encode(webpath, strbuf); CacheWriteString(cache, strbuf); CacheWriteString(cache, "</D:href>\n"); /* first comes valid props. */ CacheWriteString(cache, "\t\t<D:propstat>\n" "\t\t\t<D:prop>\n"); e = HashFirst(hash); while(e) { if(e->value.data.string[0]) { CacheWriteString(cache, "\t\t\t\t<D:"); CacheWriteString(cache, e->name); CacheWriteString(cache, ">"); CacheWriteString(cache, e->value.data.string); // just for test CacheWriteString(cache, "</D:"); CacheWriteString(cache, e->name); CacheWriteString(cache, ">\n"); } e = HashNext(hash, e); } CacheWriteString(cache, "\t\t\t</D:prop>\n" "\t\t\t<D:status>"); CacheWriteString(cache, "HTTP/1.1 200 OK"); CacheWriteString(cache, "</D:status>\n" "\t\t</D:propstat>\n"); /* then invalid props. */ CacheWriteString(cache, "\t\t<D:propstat>\n" "\t\t\t<D:prop>\n"); e = HashFirst(hash); while(e) { if(!e->value.data.string[0]) { CacheWriteString(cache, "\t\t\t\t<D:"); CacheWriteString(cache, e->name); CacheWriteString(cache, "/>\n"); } e = HashNext(hash, e); }; CacheWriteString(cache, "\t\t\t</D:prop>\n" "\t\t\t<D:status>"); CacheWriteString(cache, "HTTP/1.1 404 Not Found"); CacheWriteString(cache, "</D:status>\n" "\t\t</D:propstat>\n"); CacheWriteString(cache, "\t</D:response>\n"); return WEBDAVR_OK; }
asmlinkage long RcvMsg(pid_t *sender, void *msg, int *len, bool block){ struct Mailbox* self; struct list* hashLink; struct Message* messages; spin_lock_irq(&creationLock); if ((self = HashFind(current->tgid)) == NULL){ //Allocate and initialize the mailbox for the receiver printk(KERN_INFO "Mailbox created via rcv for %d \n", current->tgid); self = kmem_cache_alloc(mailboxCache, GFP_KERNEL); self->owner = current->tgid; self->numberofMessages = 0; self->status = false; self->message = NULL; atomic_set(&self->references, 0); self->waitingFull = 0; self->waitingEmpty = 0; init_waitqueue_head(&self->canExit); spin_lock_init(&self->lock); init_waitqueue_head(&self->notEmpty); init_waitqueue_head(&self->notFull); //Allocate and initialize the hash link for the //receiver hashLink = kmem_cache_alloc(listCache, GFP_KERNEL); hashLink->mailbox = self; hashLink->pid = current->tgid; hashLink->next = NULL; HashAdd(current->tgid, hashLink); } atomic_add(1, &self->references); spin_unlock_irq(&creationLock); spin_lock_irq(&self->lock); // If the mailbox of the calling process is stopped, return an error if (self->status == true && self->numberofMessages == 0){ atomic_sub(1, &self->references); wake_up_all(&self->canExit); spin_unlock_irq(&self->lock); return MAILBOX_STOPPED; } // Number of messages in the process' mailbox is 0, and block is false, // so return an error if (self->numberofMessages == 0 && block == false){ atomic_sub(1, &self->references); wake_up_all(&self->canExit); spin_unlock_irq(&self->lock); return MAILBOX_EMPTY; } // Process' mailbox is empty and block is true, so need to wait on the wait queue until a message is sent else if (self->numberofMessages == 0 && block == true){ self->waitingEmpty++; spin_unlock_irq(&self->lock); wait_event(self->notEmpty, (self->numberofMessages > 0 || self->status == true)); spin_lock_irq(&self->lock); self->waitingEmpty--; if (self->waitingEmpty == 0){ wake_up(&self->canExit); } if (self->status == true){ self->waitingEmpty--; atomic_sub(1, &self->references); wake_up_all(&self->canExit); spin_unlock_irq(&self->lock); return MAILBOX_STOPPED; } } // Fills the given pointers with the data that was contained in the message messages = self->message; if(copy_to_user(sender, &messages->sender, sizeof(pid_t)) || copy_to_user(len, &messages->length, sizeof(int)) || copy_to_user(msg, messages->msg, messages->length)){ atomic_sub(1, &self->references); wake_up_all(&self->canExit); spin_unlock_irq(&self->lock); return MSG_ARG_ERROR; } self->message = self->message->next; kmem_cache_free(contentCache, messages->msg); kmem_cache_free(messageCache, messages); self->numberofMessages--; wake_up_all(&self->notFull); atomic_sub(1, &self->references); wake_up_all(&self->canExit); spin_unlock_irq(&self->lock); return 0; }