您当前的位置:首页 > IT编程 > C++
| C语言 | Java | VB | VC | python | Android | TensorFlow | C++ | oracle | 学术与代码 | cnn卷积神经网络 | gnn | 图像修复 | Keras | 数据集 | Neo4j | 自然语言处理 | 深度学习 | 医学CAD | 医学影像 | 超参数 | pointnet | pytorch | 异常检测 | Transformers | 情感分类 | 知识图谱 |

自学教程:C++ zmalloc函数代码示例

51自学网 2021-06-03 12:00:47
  C++
这篇教程C++ zmalloc函数代码示例写得很实用,希望能帮到您。

本文整理汇总了C++中zmalloc函数的典型用法代码示例。如果您正苦于以下问题:C++ zmalloc函数的具体用法?C++ zmalloc怎么用?C++ zmalloc使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。

在下文中一共展示了zmalloc函数的30个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: put

 * * if contains key * 		extract list no to tail, free old value(Is there any consistent problem?), update list pair value, * else * 		if FULL * 			delete list head and delete head (key, value) in map * 		add key value to list tail and put (key, list node address) to map * * 	There is a problem, if cache is full, new node will replace one old node and old node will be released, * 	object who owns the old node value will make error, so we strongly recommend to transport a value_dup function * 	to the cache, on which we will try to return a value dup_copy to the object. */static void put(lru_cache_t *this, sds key, void *value) {	void *v = this->map->op->get(this->map, key);	pair_t *p = zmalloc(sizeof(pair_t));	p->key = sds_dup(key);	p->value = this->value_dup ? this->value_dup(value) : value;	if(v == NULL) {		if(this->max_size == this->list->len) {			//if full, delete list head,			this->map->op->del(this->map, ((pair_t *)(this->list->head->value))->key);			this->list->list_ops->list_del_node(this->list, this->list->head);		}		this->list->list_ops->list_add_node_tail(this->list, p);	}else {		//delete old key-value in list		list_node_t **node = v;		if(this->list->free) {
开发者ID:Binyang2014,项目名称:filesystem,代码行数:31,


示例2: return

gv_argvlist_t *gvNEWargvlist(void){    return (gv_argvlist_t*)zmalloc(sizeof(gv_argvlist_t));}
开发者ID:CharlieSa,项目名称:livizjs,代码行数:4,


示例3: luaRedisGenericCommand

int luaRedisGenericCommand(lua_State *lua, int raise_error) {    int j, argc = lua_gettop(lua);    struct redisCommand *cmd;    robj **argv;    redisClient *c = server.lua_client;    sds reply;    /* Require at least one argument */    if (argc == 0) {        luaPushError(lua,            "Please specify at least one argument for redis.call()");        return 1;    }    /* Build the arguments vector */    argv = zmalloc(sizeof(robj*)*argc);    for (j = 0; j < argc; j++) {        if (!lua_isstring(lua,j+1)) break;        argv[j] = createStringObject((char*)lua_tostring(lua,j+1),                                     lua_strlen(lua,j+1));    }        /* Check if one of the arguments passed by the Lua script     * is not a string or an integer (lua_isstring() return true for     * integers as well). */    if (j != argc) {        j--;        while (j >= 0) {            decrRefCount(argv[j]);            j--;        }        zfree(argv);        luaPushError(lua,            "Lua redis() command arguments must be strings or integers");        return 1;    }    /* Setup our fake client for command execution */    c->argv = argv;    c->argc = argc;    /* Command lookup */    cmd = lookupCommand(argv[0]->ptr);    if (!cmd || ((cmd->arity > 0 && cmd->arity != argc) ||                   (argc < -cmd->arity)))    {        if (cmd)            luaPushError(lua,                "Wrong number of args calling Redis command From Lua script");        else            luaPushError(lua,"Unknown Redis command called from Lua script");        goto cleanup;    }    /* There are commands that are not allowed inside scripts. */    if (cmd->flags & REDIS_CMD_NOSCRIPT) {        luaPushError(lua, "This Redis command is not allowed from scripts");        goto cleanup;    }    /* Write commands are forbidden against read-only slaves, or if a     * command marked as non-deterministic was already called in the context     * of this script. */    if (cmd->flags & REDIS_CMD_WRITE) {        if (server.lua_random_dirty) {            luaPushError(lua,                "Write commands not allowed after non deterministic commands");            goto cleanup;        } else if (server.masterhost && server.repl_slave_ro &&                   !server.loading &&                   !(server.lua_caller->flags & REDIS_MASTER))        {            luaPushError(lua, shared.roslaveerr->ptr);            goto cleanup;        } else if (server.stop_writes_on_bgsave_err &&                   server.saveparamslen > 0 &&                   server.lastbgsave_status == REDIS_ERR)        {            luaPushError(lua, shared.bgsaveerr->ptr);            goto cleanup;        }    }    /* If we reached the memory limit configured via maxmemory, commands that     * could enlarge the memory usage are not allowed, but only if this is the     * first write in the context of this script, otherwise we can't stop     * in the middle. */    if (server.maxmemory && server.lua_write_dirty == 0 &&        (cmd->flags & REDIS_CMD_DENYOOM))    {        if (freeMemoryIfNeeded() == REDIS_ERR) {            luaPushError(lua, shared.oomerr->ptr);            goto cleanup;        }    }    if (cmd->flags & REDIS_CMD_RANDOM) server.lua_random_dirty = 1;    if (cmd->flags & REDIS_CMD_WRITE) server.lua_write_dirty = 1;    /* Run the command *///.........这里部分代码省略.........
开发者ID:Whitespace,项目名称:redis,代码行数:101,


示例4: zunionInterGenericCommand

void zunionInterGenericCommand(redisClient *c, robj *dstkey, int op) {    int i, j, setnum;    int aggregate = REDIS_AGGR_SUM;    zsetopsrc *src;    robj *dstobj;    zset *dstzset;    zskiplistNode *znode;    dictIterator *di;    dictEntry *de;    int touched = 0;    /* expect setnum input keys to be given */    setnum = atoi(c->argv[2]->ptr);    if (setnum < 1) {        addReplyError(c,            "at least 1 input key is needed for ZUNIONSTORE/ZINTERSTORE");        return;    }    /* test if the expected number of keys would overflow */    if (3+setnum > c->argc) {        addReply(c,shared.syntaxerr);        return;    }    /* read keys to be used for input */    src = zmalloc(sizeof(zsetopsrc) * setnum);    for (i = 0, j = 3; i < setnum; i++, j++) {        robj *obj = lookupKeyWrite(c->db,c->argv[j]);        if (!obj) {            src[i].dict = NULL;        } else {            if (obj->type == REDIS_ZSET) {                src[i].dict = ((zset*)obj->ptr)->dict;            } else if (obj->type == REDIS_SET) {                src[i].dict = (obj->ptr);            } else {                zfree(src);                addReply(c,shared.wrongtypeerr);                return;            }        }        /* default all weights to 1 */        src[i].weight = 1.0;    }    /* parse optional extra arguments */    if (j < c->argc) {        int remaining = c->argc - j;        while (remaining) {            if (remaining >= (setnum + 1) && !strcasecmp(c->argv[j]->ptr,"weights")) {                j++; remaining--;                for (i = 0; i < setnum; i++, j++, remaining--) {                    if (getDoubleFromObjectOrReply(c,c->argv[j],&src[i].weight,                            "weight value is not a double") != REDIS_OK)                    {                        zfree(src);                        return;                    }                }            } else if (remaining >= 2 && !strcasecmp(c->argv[j]->ptr,"aggregate")) {                j++; remaining--;                if (!strcasecmp(c->argv[j]->ptr,"sum")) {                    aggregate = REDIS_AGGR_SUM;                } else if (!strcasecmp(c->argv[j]->ptr,"min")) {                    aggregate = REDIS_AGGR_MIN;                } else if (!strcasecmp(c->argv[j]->ptr,"max")) {                    aggregate = REDIS_AGGR_MAX;                } else {                    zfree(src);                    addReply(c,shared.syntaxerr);                    return;                }                j++; remaining--;            } else {                zfree(src);                addReply(c,shared.syntaxerr);                return;            }        }    }    /* sort sets from the smallest to largest, this will improve our     * algorithm's performance */    qsort(src,setnum,sizeof(zsetopsrc),qsortCompareZsetopsrcByCardinality);    dstobj = createZsetObject();    dstzset = dstobj->ptr;    if (op == REDIS_OP_INTER) {        /* skip going over all entries if the smallest zset is NULL or empty */        if (src[0].dict && dictSize(src[0].dict) > 0) {            /* precondition: as src[0].dict is non-empty and the zsets are ordered             * from small to large, all src[i > 0].dict are non-empty too */            di = dictGetIterator(src[0].dict);            while((de = dictNext(di)) != NULL) {                double score, value;//.........这里部分代码省略.........
开发者ID:JakSprats,项目名称:Alchemy-Database,代码行数:101,


示例5: zmalloc

redisSortOperation *createSortOperation(int type, robj *pattern) {    redisSortOperation *so = zmalloc(sizeof(*so));    so->type = type;    so->pattern = pattern;    return so;}
开发者ID:JoonyLi,项目名称:redis-android,代码行数:6,


示例6: smemgetCommand

void smemgetCommand(client *c){    long long ll_size;    int size;    int mem_id = -1;    listNode *ln;    listIter li;    struct smem_t * smem_p = NULL;    // check the size    if(getLongLongFromObject(c->argv[1],&ll_size) == C_OK){        //serverLog(LL_WARNING,"[smemgetCommand] will get share memory size: %lld", ll_size);        size = ll_size;                // get buffer from list        listRewind(server.smem_list_available, &li);        while ((ln = listNext(&li)) != NULL) {            smem_p = ln->value;            // compare the size            if((smem_p->state == SMEM_T_STATE_AVAILAVLE) && (size <= smem_p->size)){                                smem_p->state = SMEM_T_STATE_USED;                smem_p->cnt = 1;                smem_p->free_cnt = 0;                smem_p->last_time = server.unixtime;                mem_id = smem_p->id;                // move it to used list                smemlistMoveNode(server.smem_list_available, server.smem_list_used, ln);                break;            }         }                if(mem_id == -1){            // check the share memory max limit            if((server.share_memory_size + size) <= server.share_memory_limit){                // get buffer by use smem                mem_id = smem_get_buffer(size);                if(mem_id != -1){                                        smem_p = zmalloc(sizeof(struct smem_t));                    if(smem_p == NULL){                        mem_id = -1;                        serverLog(LL_WARNING,"[smemgetCommand] zmalloc failed.");                    }else{                        smem_p->id = mem_id;                        smem_p->size = size;                        smem_p->state = SMEM_T_STATE_USED;                        smem_p->cnt = 1;                        smem_p->free_cnt = 0;                        smem_p->last_time = server.unixtime;                                                // add itme to list                        listAddNodeTail(server.smem_list_used, smem_p);                        // update the share memory used status                        server.share_memory_size += size;                    }                                    }            }else{                serverLog(LL_WARNING,"[smemgetCommand] server.share_memory_size:%d + %d > server.share_memory_limit:%d", server.share_memory_size, size, server.share_memory_limit);            }        }            }    //serverLog(LL_WARNING,"[smemgetCommand] get share memory id: %d", mem_id);    addReplyLongLong(c,mem_id);    return C_OK;}
开发者ID:shenhailuanma,项目名称:selfTestCode,代码行数:81,


示例7: lttng_userspace_probe_location_tracepoint_create_no_check

static struct lttng_userspace_probe_location *lttng_userspace_probe_location_tracepoint_create_no_check(const char *binary_path,		const char *provider_name, const char *probe_name,		struct lttng_userspace_probe_location_lookup_method *lookup_method,		bool open_binary){	int binary_fd = -1;	char *probe_name_copy = NULL;	char *provider_name_copy = NULL;	char *binary_path_copy = NULL;	struct lttng_userspace_probe_location *ret = NULL;	struct lttng_userspace_probe_location_tracepoint *location;	if (open_binary) {		binary_fd = open(binary_path, O_RDONLY);		if (binary_fd < 0) {			PERROR("open");			goto error;		}	} else {		binary_fd = -1;	}	probe_name_copy = lttng_strndup(probe_name, LTTNG_SYMBOL_NAME_LEN);	if (!probe_name_copy) {		PERROR("lttng_strndup");		goto error;	}	provider_name_copy = lttng_strndup(provider_name, LTTNG_SYMBOL_NAME_LEN);	if (!provider_name_copy) {		PERROR("lttng_strndup");		goto error;	}	binary_path_copy = lttng_strndup(binary_path, LTTNG_PATH_MAX);	if (!binary_path_copy) {		PERROR("lttng_strndup");		goto error;	}	location = zmalloc(sizeof(*location));	if (!location) {		PERROR("zmalloc");		goto error;	}	location->probe_name = probe_name_copy;	location->provider_name = provider_name_copy;	location->binary_path = binary_path_copy;	location->binary_fd = binary_fd;	ret = &location->parent;	ret->lookup_method = lookup_method;	ret->type = LTTNG_USERSPACE_PROBE_LOCATION_TYPE_TRACEPOINT;	goto end;error:	free(probe_name_copy);	free(provider_name_copy);	free(binary_path_copy);	if (binary_fd >= 0) {		if (close(binary_fd)) {			PERROR("Error closing binary fd in error path");		}	}end:	return ret;}
开发者ID:lttng,项目名称:lttng-tools,代码行数:69,


示例8: sinterGenericCommand

void sinterGenericCommand(redisClient *c, robj **setkeys, unsigned long setnum, robj *dstkey) {    robj **sets = zmalloc(sizeof(robj*)*setnum);    setTypeIterator *si;    robj *eleobj, *dstset = NULL;    int64_t intobj;    void *replylen = NULL;    unsigned long j, cardinality = 0;    int encoding;    for (j = 0; j < setnum; j++) {        robj *setobj = dstkey ?            lookupKeyWrite(c->db,setkeys[j]) :            lookupKeyRead(c->db,setkeys[j]);        if (!setobj) {            zfree(sets);            if (dstkey) {                if (dbDelete(c->db,dstkey)) {                    touchWatchedKey(c->db,dstkey);                    server.dirty++;                }                addReply(c,shared.czero);            } else {                addReply(c,shared.emptymultibulk);            }            return;        }        if (checkType(c,setobj,REDIS_SET)) {            zfree(sets);            return;        }        sets[j] = setobj;    }    /* Sort sets from the smallest to largest, this will improve our     * algorithm's performace */    qsort(sets,setnum,sizeof(robj*),qsortCompareSetsByCardinality);    /* The first thing we should output is the total number of elements...     * since this is a multi-bulk write, but at this stage we don't know     * the intersection set size, so we use a trick, append an empty object     * to the output list and save the pointer to later modify it with the     * right length */    if (!dstkey) {        replylen = addDeferredMultiBulkLength(c);    } else {        /* If we have a target key where to store the resulting set         * create this key with an empty set inside */        dstset = createIntsetObject();    }    /* Iterate all the elements of the first (smallest) set, and test     * the element against all the other sets, if at least one set does     * not include the element it is discarded */    si = setTypeInitIterator(sets[0]);    while((encoding = setTypeNext(si,&eleobj,&intobj)) != -1) {        for (j = 1; j < setnum; j++) {            if (encoding == REDIS_ENCODING_INTSET) {                /* intset with intset is simple... and fast */                if (sets[j]->encoding == REDIS_ENCODING_INTSET &&                    !intsetFind((intset*)sets[j]->ptr,intobj))                {                    break;                /* in order to compare an integer with an object we                 * have to use the generic function, creating an object                 * for this */                } else if (sets[j]->encoding == REDIS_ENCODING_HT) {                    eleobj = createStringObjectFromLongLong(intobj);                    if (!setTypeIsMember(sets[j],eleobj)) {                        decrRefCount(eleobj);                        break;                    }                    decrRefCount(eleobj);                }            } else if (encoding == REDIS_ENCODING_HT) {                /* Optimization... if the source object is integer                 * encoded AND the target set is an intset, we can get                 * a much faster path. */                if (eleobj->encoding == REDIS_ENCODING_INT &&                    sets[j]->encoding == REDIS_ENCODING_INTSET &&                    !intsetFind((intset*)sets[j]->ptr,(long)eleobj->ptr))                {                    break;                /* else... object to object check is easy as we use the                 * type agnostic API here. */                } else if (!setTypeIsMember(sets[j],eleobj)) {                    break;                }            }        }        /* Only take action when all sets contain the member */        if (j == setnum) {            if (!dstkey) {                if (encoding == REDIS_ENCODING_HT)                    addReplyBulk(c,eleobj);                else                    addReplyBulkLongLong(c,intobj);                cardinality++;            } else {                if (encoding == REDIS_ENCODING_INTSET) {                    eleobj = createStringObjectFromLongLong(intobj);//.........这里部分代码省略.........
开发者ID:jrun,项目名称:redis,代码行数:101,


示例9: sunionDiffGenericCommand

void sunionDiffGenericCommand(redisClient *c, robj **setkeys, int setnum, robj *dstkey, int op) {    robj **sets = zmalloc(sizeof(robj*)*setnum);    setTypeIterator *si;    robj *ele, *dstset = NULL;    int j, cardinality = 0;    for (j = 0; j < setnum; j++) {        robj *setobj = dstkey ?            lookupKeyWrite(c->db,setkeys[j]) :            lookupKeyRead(c->db,setkeys[j]);        if (!setobj) {            sets[j] = NULL;            continue;        }        if (checkType(c,setobj,REDIS_SET)) {            zfree(sets);            return;        }        sets[j] = setobj;    }    /* We need a temp set object to store our union. If the dstkey     * is not NULL (that is, we are inside an SUNIONSTORE operation) then     * this set object will be the resulting object to set into the target key*/    dstset = createIntsetObject();    /* Iterate all the elements of all the sets, add every element a single     * time to the result set */    for (j = 0; j < setnum; j++) {        if (op == REDIS_OP_DIFF && j == 0 && !sets[j]) break; /* result set is empty */        if (!sets[j]) continue; /* non existing keys are like empty sets */        si = setTypeInitIterator(sets[j]);        while((ele = setTypeNextObject(si)) != NULL) {            if (op == REDIS_OP_UNION || j == 0) {                if (setTypeAdd(dstset,ele)) {                    cardinality++;                }            } else if (op == REDIS_OP_DIFF) {                if (setTypeRemove(dstset,ele)) {                    cardinality--;                }            }            decrRefCount(ele);        }        setTypeReleaseIterator(si);        /* Exit when result set is empty. */        if (op == REDIS_OP_DIFF && cardinality == 0) break;    }    /* Output the content of the resulting set, if not in STORE mode */    if (!dstkey) {        addReplyMultiBulkLen(c,cardinality);        si = setTypeInitIterator(dstset);        while((ele = setTypeNextObject(si)) != NULL) {            addReplyBulk(c,ele);            decrRefCount(ele);        }        setTypeReleaseIterator(si);        decrRefCount(dstset);    } else {        /* If we have a target key where to store the resulting set         * create this key with the result set inside */        dbDelete(c->db,dstkey);        if (setTypeSize(dstset) > 0) {            dbAdd(c->db,dstkey,dstset);            addReplyLongLong(c,setTypeSize(dstset));        } else {            decrRefCount(dstset);            addReply(c,shared.czero);        }        touchWatchedKey(c->db,dstkey);        server.dirty++;    }    zfree(sets);}
开发者ID:jrun,项目名称:redis,代码行数:77,


示例10: triggleGenericCommand

void triggleGenericCommand(redisClient *c, int nx, robj *db_id, robj *key_pattern,robj *event_type, robj *script_source) {    redisLog(REDIS_NOTICE,"dbid: %s keypattern: %s script_source: %s ",db_id->ptr,key_pattern->ptr,script_source->ptr);    int id = atoi(db_id->ptr);    int int_event=process_trigglecmd(event_type->ptr);    if(int_event==-1)    {        addReplyError(c,"undefine event in redis triggle");        return;    }        //redisLog(REDIS_NOTICE,"get event:%d for: %s",int_event,event_type->ptr);    if(id<0||id>server.dbnum)    {        addReplyError(c,"wrong dbid for triggle");        return;    }//    redisLog(REDIS_NOTICE,"add  into stack: %d",lua_gettop(server.lua));    /*lua_check*/    sds funcdef = sdsempty();    funcdef = sdscat(funcdef,"function ");    funcdef = sdscatlen(funcdef,key_pattern->ptr,sdslen(key_pattern->ptr));    funcdef = sdscatlen(funcdef,"() ",3);    funcdef = sdscatlen(funcdef,script_source->ptr,sdslen(script_source->ptr));    funcdef = sdscatlen(funcdef," end",4);    //redisLog(REDIS_NOTICE,"script function:%s",funcdef);    if (luaL_loadbuffer(server.lua,funcdef,sdslen(funcdef),"@user_script")) {        addReplyErrorFormat(c,"Error compiling script (new function): %s/n",                lua_tostring(server.lua,-1));        lua_pop(server.lua,1);        sdsfree(funcdef);        return ;    }    sdsfree(funcdef);    //redisLog(REDIS_NOTICE,"add load buffer stack: %d",lua_gettop(server.lua));    if (lua_pcall(server.lua,0,0,0)) {        addReplyErrorFormat(c,"Error running script (new function): %s/n",                lua_tostring(server.lua,-1));        lua_pop(server.lua,1);        return ;    }    //redisLog(REDIS_NOTICE,"run buffer stack: %d",lua_gettop(server.lua));       struct bridge_db_triggle_t *tmptrg=zmalloc(sizeof(struct bridge_db_triggle_t));    tmptrg->dbid=id;    tmptrg->event=int_event;    tmptrg->lua_scripts=script_source;    incrRefCount(script_source);    sds copy=sdsdup(key_pattern->ptr);    dictAdd(server.bridge_db.triggle_scipts[id],copy,tmptrg);    addReply(c, nx ? shared.cone : shared.ok);}
开发者ID:crestxu,项目名称:redis-triggle,代码行数:62,


示例11: msaddCommand

void msaddCommand(redisClient *c) {    int setnum, valnum;    int i, j;    robj **sets;    setnum = atoi(c->argv[1]->ptr);    valnum = atoi(c->argv[2]->ptr);    if (setnum < 1) {        addReplyError(c,            "at least 1 input key is needed for MSADD");        return;    }    if (valnum < 1) {        addReplyError(c,            "at least 1 input value is needed for MSADD");        return;    }     /* test if the expected number of keys would overflow */    if (3+setnum+valnum > c->argc) {        addReply(c,shared.syntaxerr);        return;    }    int useintset = 0;    for (j = 0; j < valnum; j++) {        robj *value = c->argv[3 + setnum + j];        if (isObjectRepresentableAsLongLong(value,NULL) != REDIS_OK) {            useintset = 1;            break;        }    }    sets = zmalloc(sizeof(robj*)*setnum);    int notset = 0;    for (i = 0; i < setnum; i++) {        robj *key = c->argv[3 + i];        robj *set = lookupKeyWrite(c->db, key);        if (set == NULL) {            if (useintset == 1)                set = createIntsetObject();            else                set = createSetObject();            dbAdd(c->db,key,set);        } else {            if (set->type != REDIS_SET) {                notset = 1;                break;            }        }        sets[i] = set;    }    if (notset == 1) {        addReply(c,shared.wrongtypeerr);    } else {        long long inserted = 0;        for (i = 0; i < setnum; i++) {            for (j = 0; j < valnum; j++) {                robj *key = c->argv[3 + i];                robj *value = c->argv[3 + setnum + j];                robj *set = sets[i];                if (setTypeAdd(set,value)) {                    touchWatchedKey(c->db,key);                    server.dirty++;                    inserted++;                }            }        }        addReplyLongLong(c,inserted);    }    zfree(sets); }
开发者ID:jrun,项目名称:redis,代码行数:75,


示例12: zmalloc

/* Create an empty intset. */intset *intsetNew(void) {    intset *is = zmalloc(sizeof(intset));    is->encoding = intrev32ifbe(INTSET_ENC_INT16);    is->length = 0;    return is;}
开发者ID:xiaowei0516,项目名称:redis_comment,代码行数:7,


示例13: handler

static void handler (zsock_t *pipe, void *args) {    curl_global_init(CURL_GLOBAL_ALL);    CURLM *multi = curl_multi_init ();    CURLSH *share = curl_share_init ();    curl_share_setopt (share, CURLSHOPT_SHARE, CURL_LOCK_DATA_DNS);    curl_share_setopt (share, CURLSHOPT_SHARE, CURL_LOCK_DATA_SSL_SESSION);    curl_share_setopt (share, CURLSHOPT_SHARE, CURL_LOCK_DATA_CONNECT);    long verbose = (*(bool *) args) ? 1L : 0L;    long timeout = 30;    CURLMcode code;    SOCKET pipefd = zsock_fd (pipe);    struct curl_waitfd waitfd = {pipefd, CURL_WAIT_POLLIN};    //  List to hold pending curl handles, in case we are destroy the client    //  while request are inprogress    zlistx_t *pending_handles = zlistx_new ();    zlistx_set_destructor (pending_handles, (zlistx_destructor_fn *) curl_destructor);    zsock_signal (pipe, 0);    bool terminated = false;    while (!terminated) {        int events = zsock_events (pipe);        if ((events & ZMQ_POLLIN) == 0) {            code = curl_multi_wait (multi, &waitfd, 1, 1000, NULL);            assert (code == CURLM_OK);        }        events = zsock_events (pipe);        if (events & ZMQ_POLLIN) {            char* command = zstr_recv (pipe);            if (!command)                break;          //  Interrupted            //  All actors must handle $TERM in this way            if (streq (command, "$TERM"))                terminated = true;            else if (streq (command, "GET")) {                char *url;                zlistx_t *headers;                void *userp;                int rc = zsock_recv (pipe, "slp", &url, &headers, &userp);                assert (rc == 0);                zchunk_t *data = zchunk_new (NULL, 100);                assert (data);                struct curl_slist *curl_headers = zlistx_to_slist (headers);                CURL *curl = curl_easy_init ();                zlistx_add_end (pending_handles, curl);                http_request *request = (http_request *) zmalloc (sizeof (http_request));                assert (request);                request->userp = userp;                request->curl = curl;                request->data = data;                request->headers = curl_headers;                curl_easy_setopt (curl, CURLOPT_SHARE, share);                curl_easy_setopt (curl, CURLOPT_TIMEOUT, timeout);                curl_easy_setopt (curl, CURLOPT_VERBOSE, verbose);                curl_easy_setopt (curl, CURLOPT_HTTPHEADER, curl_headers);                curl_easy_setopt (curl, CURLOPT_URL, url);                curl_easy_setopt (curl, CURLOPT_WRITEFUNCTION, write_data);                curl_easy_setopt (curl, CURLOPT_WRITEDATA, data);                curl_easy_setopt (curl, CURLOPT_PRIVATE, request);                code = curl_multi_add_handle (multi, curl);                assert (code == CURLM_OK);                zlistx_destroy (&headers);                zstr_free (&url);           }           else {               puts ("E: invalid message to actor");               assert (false);           }           zstr_free (&command);        }        int still_running;        code = curl_multi_perform (multi, &still_running);        assert (code == CURLM_OK);        int msgq = 0;        struct CURLMsg *msg = curl_multi_info_read(multi, &msgq);        while (msg) {            if(msg->msg == CURLMSG_DONE) {                CURL *curl = msg->easy_handle;                http_request *request;                curl_easy_getinfo(curl, CURLINFO_PRIVATE, &request);                long response_code_long;                curl_easy_getinfo (curl, CURLINFO_RESPONSE_CODE, &response_code_long);                int response_code = (int)response_code_long;                int rc = zsock_send (pipe, "icp", response_code, request->data, request->userp);                assert (rc == 0);                curl_multi_remove_handle (multi, curl);//.........这里部分代码省略.........
开发者ID:jimklimov,项目名称:czmq,代码行数:101,


示例14: zyre_event_new

zyre_event_t *zyre_event_new (zyre_t *node){    zmsg_t *msg = zyre_recv (node);    if (!msg)        return NULL;            //  Interrupted    zyre_event_t *self = (zyre_event_t *) zmalloc (sizeof (zyre_event_t));    assert (self);    char *type = zmsg_popstr (msg);    self->sender = zmsg_popstr (msg);    self->name = zmsg_popstr (msg);    if (streq (type, "ENTER")) {        self->type = ZYRE_EVENT_ENTER;        zframe_t *headers = zmsg_pop (msg);        if (headers) {            self->headers = zhash_unpack (headers);            zframe_destroy (&headers);        }        self->address = zmsg_popstr (msg);    }    else    if (streq (type, "EXIT"))        self->type = ZYRE_EVENT_EXIT;    else    if (streq (type, "JOIN")) {        self->type = ZYRE_EVENT_JOIN;        self->group = zmsg_popstr (msg);    }    else    if (streq (type, "LEAVE")) {        self->type = ZYRE_EVENT_LEAVE;        self->group = zmsg_popstr (msg);    }    else    if (streq (type, "WHISPER")) {        self->type = ZYRE_EVENT_WHISPER;        self->msg = msg;        msg = NULL;    }    else    if (streq (type, "SHOUT")) {        self->type = ZYRE_EVENT_SHOUT;        self->group = zmsg_popstr (msg);        self->msg = msg;        msg = NULL;    }    else    if (streq (type, "STOP")) {        self->type = ZYRE_EVENT_STOP;    }    else    if (streq (type, "EVASIVE")) {        self->type = ZYRE_EVENT_EVASIVE;    }    else        zsys_warning ("bad message received from node: %s/n", type);    free (type);    zmsg_destroy (&msg);    return self;}
开发者ID:GameFilebyOpenSourse,项目名称:zyre,代码行数:64,


示例15: symbol_number

symbol_t * symbol_number(long double d) {    symbol_t *s = (symbol_t*)zmalloc(sizeof(symbol_t));    s->type = stNumber;    s->number = d;    return s;}
开发者ID:rodolf0,项目名称:natools,代码行数:6,


示例16: createClient

/* Create a benchmark client, configured to send the command passed as 'cmd' of * 'len' bytes. * * The command is copied N times in the client output buffer (that is reused * again and again to send the request to the server) accordingly to the configured * pipeline size. * * Also an initial SELECT command is prepended in order to make sure the right * database is selected, if needed. The initial SELECT will be discarded as soon * as the first reply is received. * * To create a client from scratch, the 'from' pointer is set to NULL. If instead * we want to create a client using another client as reference, the 'from' pointer * points to the client to use as reference. In such a case the following * information is take from the 'from' client: * * 1) The command line to use. * 2) The offsets of the __rand_int__ elements inside the command line, used *    for arguments randomization. * * Even when cloning another client, prefix commands are applied if needed.*/static client createClient(char *cmd, size_t len, client from) {    int j;    client c = zmalloc(sizeof(struct _client));    if (config.hostsocket == NULL) {        c->context = redisConnectNonBlock(config.hostip,config.hostport);    } else {        c->context = redisConnectUnixNonBlock(config.hostsocket);    }    if (c->context->err) {        fprintf(stderr,"Could not connect to Redis at ");        if (config.hostsocket == NULL)            fprintf(stderr,"%s:%d: %s/n",config.hostip,config.hostport,c->context->errstr);        else            fprintf(stderr,"%s: %s/n",config.hostsocket,c->context->errstr);        exit(1);    }    /* Suppress hiredis cleanup of unused buffers for max speed. */    c->context->reader->maxbuf = 0;    /* Build the request buffer:     * Queue N requests accordingly to the pipeline size, or simply clone     * the example client buffer. */    c->obuf = sdsempty();    /* Prefix the request buffer with AUTH and/or SELECT commands, if applicable.     * These commands are discarded after the first response, so if the client is     * reused the commands will not be used again. */    c->prefix_pending = 0;    if (config.auth) {        char *buf = NULL;        int len = redisFormatCommand(&buf, "AUTH %s", config.auth);        c->obuf = sdscatlen(c->obuf, buf, len);        free(buf);        c->prefix_pending++;    }    /* If a DB number different than zero is selected, prefix our request     * buffer with the SELECT command, that will be discarded the first     * time the replies are received, so if the client is reused the     * SELECT command will not be used again. */    if (config.dbnum != 0) {        c->obuf = sdscatprintf(c->obuf,"*2/r/n$6/r/nSELECT/r/n$%d/r/n%s/r/n",            (int)sdslen(config.dbnumstr),config.dbnumstr);        c->prefix_pending++;    }    c->prefixlen = sdslen(c->obuf);    /* Append the request itself. */    if (from) {        c->obuf = sdscatlen(c->obuf,            from->obuf+from->prefixlen,            sdslen(from->obuf)-from->prefixlen);    } else {        for (j = 0; j < config.pipeline; j++)            c->obuf = sdscatlen(c->obuf,cmd,len);    }    c->written = 0;    c->pending = config.pipeline+c->prefix_pending;    c->randptr = NULL;    c->randlen = 0;    /* Find substrings in the output buffer that need to be randomized. */    if (config.randomkeys) {        if (from) {            c->randlen = from->randlen;            c->randfree = 0;            c->randptr = zmalloc(sizeof(char*)*c->randlen);            /* copy the offsets. */            for (j = 0; j < (int)c->randlen; j++) {                c->randptr[j] = c->obuf + (from->randptr[j]-from->obuf);                /* Adjust for the different select prefix length. */                c->randptr[j] += c->prefixlen - from->prefixlen;            }        } else {            char *p = c->obuf;            c->randlen = 0;            c->randfree = RANDPTR_INITIAL_SIZE;            c->randptr = zmalloc(sizeof(char*)*c->randfree);//.........这里部分代码省略.........
开发者ID:JunyaShirahama,项目名称:tweeter,代码行数:101,


示例17: parser_eval

int parser_eval(const expr_t *e, long double *r, hashtbl_t *vars) {    if (!e || !r) {        fprintf(stderr, "eval error: null expression or result var/n");        return 1;    }    /* load known functions */    static hashtbl_t *functions = NULL;    if (unlikely(functions == NULL)) {        functions = hashtbl_init(NULL, NULL);        register_functions(functions);    }    /* stash constants into whatever symtab we get */    if (unlikely(vars && !hashtbl_get(vars, "_stashed"))) {        register_constants(vars);    }    const list_t *l = (const list_t*)e;    const list_node_t *n = list_last(l);    list_t *args = list_init(free, NULL);    const symbol_t *s;    while (n && (s = (const symbol_t*)list_data(n))) {        long double *d = NULL, *v = NULL;        long double (*f)(list_t*, size_t);        switch (s->type) {        case stNumber:            d = (long double*)zmalloc(sizeof(long double));            *d = s->number;            list_push(args, d);            break;        case stVariable:            if (!vars) {                fprintf(stderr, "eval error: no symbol table/n");                list_destroy(args);                return 1;            }            if (!(v = (long double*)hashtbl_get(vars, s->variable))) {                fprintf(stderr, "eval error: uninitialized variable [%s]/n", s->variable);                list_destroy(args);                return 1;            }            d = (long double*)zmalloc(sizeof(long double));            *d = *v;            list_push(args, d);            break;        case stBinOperator:            /* rhs operand */            if (!(v = (long double*)list_pop(args))) {                fprintf(stderr, "eval error: missing rhs operand/n");                list_destroy(args);                return 1;            }        case stUniOperator:            /* lhs operand, don't pop it... use it to store the result too */            if (!(d = (long double*)list_peek_head(args))) {                fprintf(stderr, "eval error: missing lhs operand/n");                list_destroy(args);                return 1;            }            *d = semanter_operator(s->operator, *d, s->type == stBinOperator ? *v : 0.0);            free(v);            break;        case stFunction:            if (!(f = (long double(*)(list_t*, size_t))hashtbl_get(functions, s->func.name))) {                fprintf(stderr, "eval error: unknown function [%s]/n", s->func.name);                list_destroy(args);                return 1;            }            d = (long double*)zmalloc(sizeof(long double));            *d = f(args, s->func.nargs);            list_push(args, d);            break;        }        n = list_prev(n);    }    if (list_size(args) != 1) {        fprintf(stderr, "eval error: corrupt args stack/n");        list_destroy(args);        return 1;    }    long double *d = (long double*)list_peek_head(args);    *r = *d;    list_destroy(args);    return 0;}
开发者ID:rodolf0,项目名称:natools,代码行数:92,


示例18: main

int main(int argc, const char **argv) {    int i;    char *data, *cmd;    int len;    client c;    srandom(time(NULL));    signal(SIGHUP, SIG_IGN);    signal(SIGPIPE, SIG_IGN);    config.numclients = 50;    config.requests = 100000;    config.liveclients = 0;    config.el = aeCreateEventLoop(1024*10);    aeCreateTimeEvent(config.el,1,showThroughput,NULL,NULL);    config.keepalive = 1;    config.datasize = 3;    config.pipeline = 1;    config.showerrors = 0;    config.randomkeys = 0;    config.randomkeys_keyspacelen = 0;    config.quiet = 0;    config.csv = 0;    config.loop = 0;    config.idlemode = 0;    config.latency = NULL;    config.clients = listCreate();    config.hostip = "127.0.0.1";    config.hostport = 6379;    config.hostsocket = NULL;    config.tests = NULL;    config.dbnum = 0;    config.auth = NULL;    i = parseOptions(argc,argv);    argc -= i;    argv += i;    config.latency = zmalloc(sizeof(long long)*config.requests);    if (config.keepalive == 0) {        printf("WARNING: keepalive disabled, you probably need 'echo 1 > /proc/sys/net/ipv4/tcp_tw_reuse' for Linux and 'sudo sysctl -w net.inet.tcp.msl=1000' for Mac OS X in order to use a lot of clients/requests/n");    }    if (config.idlemode) {        printf("Creating %d idle connections and waiting forever (Ctrl+C when done)/n", config.numclients);        c = createClient("",0,NULL); /* will never receive a reply */        createMissingClients(c);        aeMain(config.el);        /* and will wait for every */    }    /* Run benchmark with command in the remainder of the arguments. */    if (argc) {        sds title = sdsnew(argv[0]);        for (i = 1; i < argc; i++) {            title = sdscatlen(title, " ", 1);            title = sdscatlen(title, (char*)argv[i], strlen(argv[i]));        }        do {            len = redisFormatCommandArgv(&cmd,argc,argv,NULL);            benchmark(title,cmd,len);            free(cmd);        } while(config.loop);        return 0;    }    /* Run default benchmark suite. */    data = zmalloc(config.datasize+1);    do {        memset(data,'x',config.datasize);        data[config.datasize] = '/0';        if (test_is_selected("ping_inline") || test_is_selected("ping"))            benchmark("PING_INLINE","PING/r/n",6);        if (test_is_selected("ping_mbulk") || test_is_selected("ping")) {            len = redisFormatCommand(&cmd,"PING");            benchmark("PING_BULK",cmd,len);            free(cmd);        }        if (test_is_selected("set")) {            len = redisFormatCommand(&cmd,"SET key:__rand_int__ %s",data);            benchmark("SET",cmd,len);            free(cmd);        }        if (test_is_selected("get")) {            len = redisFormatCommand(&cmd,"GET key:__rand_int__");            benchmark("GET",cmd,len);            free(cmd);        }        if (test_is_selected("incr")) {            len = redisFormatCommand(&cmd,"INCR counter:__rand_int__");            benchmark("INCR",cmd,len);//.........这里部分代码省略.........
开发者ID:JunyaShirahama,项目名称:tweeter,代码行数:101,


示例19: lttng_userspace_probe_location_function_create_no_check

static struct lttng_userspace_probe_location *lttng_userspace_probe_location_function_create_no_check(const char *binary_path,		const char *function_name,		struct lttng_userspace_probe_location_lookup_method *lookup_method,		bool open_binary){	int binary_fd = -1;	char *function_name_copy = NULL, *binary_path_copy = NULL;	struct lttng_userspace_probe_location *ret = NULL;	struct lttng_userspace_probe_location_function *location;	if (open_binary) {		binary_fd = open(binary_path, O_RDONLY);		if (binary_fd < 0) {			PERROR("Error opening the binary");			goto error;		}	} else {		binary_fd = -1;	}	function_name_copy = lttng_strndup(function_name, LTTNG_SYMBOL_NAME_LEN);	if (!function_name_copy) {		PERROR("Error duplicating the function name");		goto error;	}	binary_path_copy = lttng_strndup(binary_path, LTTNG_PATH_MAX);	if (!binary_path_copy) {		PERROR("Error duplicating the function name");		goto error;	}	location = zmalloc(sizeof(*location));	if (!location) {		PERROR("Error allocating userspace probe location");		goto error;	}	location->function_name = function_name_copy;	location->binary_path = binary_path_copy;	location->binary_fd = binary_fd;	location->instrumentation_type =			LTTNG_USERSPACE_PROBE_LOCATION_FUNCTION_INSTRUMENTATION_TYPE_ENTRY;	ret = &location->parent;	ret->lookup_method = lookup_method;	ret->type = LTTNG_USERSPACE_PROBE_LOCATION_TYPE_FUNCTION;	goto end;error:	free(function_name_copy);	free(binary_path_copy);	if (binary_fd >= 0) {		if (close(binary_fd)) {			PERROR("Error closing binary fd in error path");		}	}end:	return ret;}
开发者ID:lttng,项目名称:lttng-tools,代码行数:61,


示例20: zmalloc

/* Split 's' with separator in 'sep'. An array * of sds strings is returned. *count will be set * by reference to the number of tokens returned. * * On out of memory, zero length string, zero length * separator, NULL is returned. * * Note that 'sep' is able to split a string using * a multi-character separator. For example * sdssplit("foo_-_bar","_-_"); will return two * elements "foo" and "bar". * * This version of the function is binary-safe but * requires length arguments. sdssplit() is just the * same function but for zero-terminated strings. */sds *sdssplitlen(char *s, int len, char *sep, int seplen, int *count) {    int elements = 0, slots = 5, start = 0, j;    sds *tokens = zmalloc(sizeof(sds)*slots);#ifdef SDS_ABORT_ON_OOM    if (tokens == NULL) sdsOomAbort();#endif    if (seplen < 1 || len < 0 || tokens == NULL) return NULL;    if (len == 0) {        *count = 0;        return tokens;    }    for (j = 0; j < (len-(seplen-1)); j++) {        /* make sure there is room for the next element and the final one */        if (slots < elements+2) {            sds *newtokens;            slots *= 2;            newtokens = zrealloc(tokens,sizeof(sds)*slots);            if (newtokens == NULL) {#ifdef SDS_ABORT_ON_OOM                sdsOomAbort();#else                goto cleanup;#endif            }            tokens = newtokens;        }        /* search the separator */        if ((seplen == 1 && *(s+j) == sep[0]) || (memcmp(s+j,sep,seplen) == 0)) {            tokens[elements] = sdsnewlen(s+start,j-start);            if (tokens[elements] == NULL) {#ifdef SDS_ABORT_ON_OOM                sdsOomAbort();#else                goto cleanup;#endif            }            elements++;            start = j+seplen;            j = j+seplen-1; /* skip the separator */        }    }    /* Add the final element. We are sure there is room in the tokens array. */    tokens[elements] = sdsnewlen(s+start,len-start);    if (tokens[elements] == NULL) {#ifdef SDS_ABORT_ON_OOM                sdsOomAbort();#else                goto cleanup;#endif    }    elements++;    *count = elements;    return tokens;#ifndef SDS_ABORT_ON_OOMcleanup:    {        int i;        for (i = 0; i < elements; i++) sdsfree(tokens[i]);        zfree(tokens);        return NULL;    }#endif}
开发者ID:aditya,项目名称:redis,代码行数:82,


示例21: zmalloc

zskiplistNode *zslCreateNode(int level, double score, robj *obj) {    zskiplistNode *zn = zmalloc(sizeof(*zn)+level*sizeof(struct zskiplistLevel));    zn->score = score;    zn->obj = obj;    return zn;}
开发者ID:JakSprats,项目名称:Alchemy-Database,代码行数:6,


示例22: zdir_new

zdir_t *zdir_new (const char *path, const char *parent){    zdir_t *self = (zdir_t *) zmalloc (sizeof (zdir_t));    if (parent) {        self->path = (char *) malloc (strlen (path) + strlen (parent) + 2);        sprintf (self->path, "%s/%s", parent, path);    }    else        self->path = strdup (path);    self->files = zlist_new ();    self->subdirs = zlist_new ();#if (defined (WIN32))    //  On Windows, replace backslashes by normal slashes    char *path_clean_ptr = self->path;    while (*path_clean_ptr) {        if (*path_clean_ptr == '//')            *path_clean_ptr = '/';        path_clean_ptr++;    }    //  Remove any trailing slash    if (self->path [strlen (self->path) - 1] == '/')        self->path [strlen (self->path) - 1] = 0;    //  Win32 wants a wildcard at the end of the path    char *wildcard = (char *) malloc (strlen (self->path) + 3);    sprintf (wildcard, "%s/*", self->path);    WIN32_FIND_DATA entry;    HANDLE handle = FindFirstFile (wildcard, &entry);    free (wildcard);    if (handle != INVALID_HANDLE_VALUE) {        //  We have read an entry, so return those values        s_win32_populate_entry (self, &entry);        while (FindNextFile (handle, &entry))            s_win32_populate_entry (self, &entry);        FindClose (handle);    }#else    //  Remove any trailing slash    if (self->path [strlen (self->path) - 1] == '/')        self->path [strlen (self->path) - 1] = 0;    DIR *handle = opendir (self->path);    if (handle) {        //  Calculate system-specific size of dirent block        int dirent_size = offsetof (struct dirent, d_name)                        + pathconf (self->path, _PC_NAME_MAX) + 1;        struct dirent *entry = (struct dirent *) malloc (dirent_size);        struct dirent *result;        int rc = readdir_r (handle, entry, &result);        while (rc == 0 && result != NULL) {            s_posix_populate_entry (self, entry);            rc = readdir_r (handle, entry, &result);        }        free (entry);        closedir (handle);    }#endif    else {
开发者ID:AndreasBomholtz,项目名称:czmq,代码行数:62,


示例23: sortCommand

/* The SORT command is the most complex command in Redis. Warning: this code * is optimized for speed and a bit less for readability */void sortCommand(redisClient *c) {    list *operations;    unsigned int outputlen = 0;    int desc = 0, alpha = 0;    long limit_start = 0, limit_count = -1, start, end;    int j, dontsort = 0, vectorlen;    int getop = 0; /* GET operation counter */    int int_convertion_error = 0;    robj *sortval, *sortby = NULL, *storekey = NULL;    redisSortObject *vector; /* Resulting vector to sort */    /* Lookup the key to sort. It must be of the right types */    sortval = lookupKeyRead(c->db,c->argv[1]);    if (sortval && sortval->type != REDIS_SET && sortval->type != REDIS_LIST &&        sortval->type != REDIS_ZSET)    {        addReply(c,shared.wrongtypeerr);        return;    }    /* Create a list of operations to perform for every sorted element.     * Operations can be GET/DEL/INCR/DECR */    operations = listCreate();    listSetFreeMethod(operations,zfree);    j = 2;    /* Now we need to protect sortval incrementing its count, in the future     * SORT may have options able to overwrite/delete keys during the sorting     * and the sorted key itself may get destroied */    if (sortval)        incrRefCount(sortval);    else        sortval = createListObject();    /* The SORT command has an SQL-alike syntax, parse it */    while(j < c->argc) {        int leftargs = c->argc-j-1;        if (!strcasecmp(c->argv[j]->ptr,"asc")) {            desc = 0;        } else if (!strcasecmp(c->argv[j]->ptr,"desc")) {            desc = 1;        } else if (!strcasecmp(c->argv[j]->ptr,"alpha")) {            alpha = 1;        } else if (!strcasecmp(c->argv[j]->ptr,"limit") && leftargs >= 2) {            if ((getLongFromObjectOrReply(c, c->argv[j+1], &limit_start, NULL) != REDIS_OK) ||                (getLongFromObjectOrReply(c, c->argv[j+2], &limit_count, NULL) != REDIS_OK)) return;            j+=2;        } else if (!strcasecmp(c->argv[j]->ptr,"store") && leftargs >= 1) {            storekey = c->argv[j+1];            j++;        } else if (!strcasecmp(c->argv[j]->ptr,"by") && leftargs >= 1) {            sortby = c->argv[j+1];            /* If the BY pattern does not contain '*', i.e. it is constant,             * we don't need to sort nor to lookup the weight keys. */            if (strchr(c->argv[j+1]->ptr,'*') == NULL) dontsort = 1;            j++;        } else if (!strcasecmp(c->argv[j]->ptr,"get") && leftargs >= 1) {            listAddNodeTail(operations,createSortOperation(                REDIS_SORT_GET,c->argv[j+1]));            getop++;            j++;        } else {            decrRefCount(sortval);            listRelease(operations);            addReply(c,shared.syntaxerr);            return;        }        j++;    }    /* If we have STORE we need to force sorting for deterministic output     * and replication. We use alpha sorting since this is guaranteed to     * work with any input. */    if (storekey && dontsort) {        dontsort = 0;        alpha = 1;        sortby = NULL;    }    /* Destructively convert encoded sorted sets for SORT. */    if (sortval->type == REDIS_ZSET)        zsetConvert(sortval, REDIS_ENCODING_SKIPLIST);    /* Load the sorting vector with all the objects to sort */    switch(sortval->type) {    case REDIS_LIST: vectorlen = listTypeLength(sortval); break;    case REDIS_SET: vectorlen =  setTypeSize(sortval); break;    case REDIS_ZSET: vectorlen = dictSize(((zset*)sortval->ptr)->dict); break;    default: vectorlen = 0; redisPanic("Bad SORT type"); /* Avoid GCC warning */    }    vector = zmalloc(sizeof(redisSortObject)*vectorlen);    j = 0;    if (sortval->type == REDIS_LIST) {        listTypeIterator *li = listTypeInitIterator(sortval,0,REDIS_TAIL);        listTypeEntry entry;        while(listTypeNext(li,&entry)) {            vector[j].obj = listTypeGet(&entry);//.........这里部分代码省略.........
开发者ID:JoonyLi,项目名称:redis-android,代码行数:101,


示例24: zpubsub_filter_new

zpubsub_filter_t *zpubsub_filter_new (void){    zpubsub_filter_t *self = (zpubsub_filter_t *) zmalloc (sizeof (zpubsub_filter_t));    return self;}
开发者ID:lovmoen,项目名称:zlabs,代码行数:6,


示例25: execute

voidexecute(INST * cdp,		/* code ptr, start execution here */	CELL *sp,		/* eval_stack pointer */	CELL *fp)		/* frame ptr into eval_stack for				   user defined functions */{    /* some useful temporaries */    CELL *cp;    int t;    unsigned tu;    /* save state for array loops via a stack */    ALOOP_STATE *aloop_state = (ALOOP_STATE *) 0;    /* for moving the eval stack on deep recursion */    CELL *old_stack_base = 0;    CELL *old_sp = 0;#ifdef	DEBUG    CELL *entry_sp = sp;#endif    int force_exit = (end_start == 0);    if (fp) {	/* we are a function call, check for deep recursion */	if (sp > stack_danger) {	/* change stacks */	    old_stack_base = stack_base;	    old_sp = sp;	    stack_base = (CELL *) zmalloc(sizeof(CELL) * EVAL_STACK_SIZE);	    stack_danger = stack_base + DANGER;	    sp = stack_base;	    /* waste 1 slot for ANSI, actually large model msdos breaks in	       RET if we don't */#ifdef	DEBUG	    entry_sp = sp;#endif	} else	    old_stack_base = (CELL *) 0;    }    while (1) {	TRACE(("execute %s sp(%ld:%s)/n",	       da_op_name(cdp),	       (long) (sp - stack_base),	       da_type_name(sp)));	switch ((cdp++)->op) {/* HALT only used by the disassemble now ; this remains   so compilers don't offset the jump table */	case _HALT:	case _STOP:		/* only for range patterns */#ifdef	DEBUG	    if (sp != entry_sp + 1)		bozo("stop0");#endif	    return;	case _PUSHC:	    inc_sp();	    cellcpy(sp, (cdp++)->ptr);	    break;	case _PUSHD:	    inc_sp();	    sp->type = C_DOUBLE;	    sp->dval = *(double *) (cdp++)->ptr;	    break;	case _PUSHS:	    inc_sp();	    sp->type = C_STRING;	    sp->ptr = (cdp++)->ptr;	    string(sp)->ref_cnt++;	    break;	case F_PUSHA:	    cp = (CELL *) cdp->ptr;	    if (cp != field) {		if (nf < 0)		    split_field0();		if (!(cp >= NF && cp <= LAST_PFIELD)) {		    /* it is a real field $1, $2 ...		       If it is greater than $NF, we have to		       make sure it is set to ""  so that		       (++|--) and g?sub() work right		     */		    t = field_addr_to_index(cp);		    if (t > nf) {			cp->type = C_STRING;			cp->ptr = (PTR) & null_str;			null_str.ref_cnt++;		    }		}	    }	    /* fall thru *///.........这里部分代码省略.........
开发者ID:jlp765,项目名称:original-mawk,代码行数:101,


示例26: processInputBuffer

void processInputBuffer(redisClient *c) {again:    /* Before to process the input buffer, make sure the client is not     * waitig for a blocking operation such as BLPOP. Note that the first     * iteration the client is never blocked, otherwise the processInputBuffer     * would not be called at all, but after the execution of the first commands     * in the input buffer the client may be blocked, and the "goto again"     * will try to reiterate. The following line will make it return asap. */    if (c->flags & REDIS_BLOCKED || c->flags & REDIS_IO_WAIT) return;    if (c->bulklen == -1) {        /* Read the first line of the query */        char *p = strchr(c->querybuf,'/n');        size_t querylen;        if (p) {            sds query, *argv;            int argc, j;            query = c->querybuf;            c->querybuf = sdsempty();            querylen = 1+(p-(query));            if (sdslen(query) > querylen) {                /* leave data after the first line of the query in the buffer */                c->querybuf = sdscatlen(c->querybuf,query+querylen,sdslen(query)-querylen);            }            *p = '/0'; /* remove "/n" */            if (*(p-1) == '/r') *(p-1) = '/0'; /* and "/r" if any */            sdsupdatelen(query);            /* Now we can split the query in arguments */            argv = sdssplitlen(query,sdslen(query)," ",1,&argc);            sdsfree(query);            if (c->argv) zfree(c->argv);            c->argv = zmalloc(sizeof(robj*)*argc);            for (j = 0; j < argc; j++) {                if (sdslen(argv[j])) {                    c->argv[c->argc] = createObject(REDIS_STRING,argv[j]);                    c->argc++;                } else {                    sdsfree(argv[j]);                }            }            zfree(argv);            if (c->argc) {                /* Execute the command. If the client is still valid                 * after processCommand() return and there is something                 * on the query buffer try to process the next command. */                if (processCommand(c) && sdslen(c->querybuf)) goto again;            } else {                /* Nothing to process, argc == 0. Just process the query                 * buffer if it's not empty or return to the caller */                if (sdslen(c->querybuf)) goto again;            }            return;        } else if (sdslen(c->querybuf) >= REDIS_REQUEST_MAX_SIZE) {            redisLog(REDIS_VERBOSE, "Client protocol error");            freeClient(c);            return;        }    } else {        /* Bulk read handling. Note that if we are at this point           the client already sent a command terminated with a newline,           we are reading the bulk data that is actually the last           argument of the command. */        int qbl = sdslen(c->querybuf);        if (c->bulklen <= qbl) {            /* Copy everything but the final CRLF as final argument */            c->argv[c->argc] = createStringObject(c->querybuf,c->bulklen-2);            c->argc++;            c->querybuf = sdsrange(c->querybuf,c->bulklen,-1);            /* Process the command. If the client is still valid after             * the processing and there is more data in the buffer             * try to parse it. */            if (processCommand(c) && sdslen(c->querybuf)) goto again;            return;        }    }}
开发者ID:bcg,项目名称:redis,代码行数:81,


示例27: zmaster_server_register_one

static void zmaster_server_register_one(char *service_str, ZMASTER_SERVER_SERVICE * service_list){	ZMASTER_SERVER_SERVICE *service;	int type, sock_fd;	ZEVENT *zev;	___ACCEPT_CONTEXT *a_c;	char _service_str[1024];	char *stype, *uri, *p;	strcpy(_service_str, service_str);	stype = _service_str;	p = strstr(_service_str, "://");	if (p) {		*p = 0;		uri = p + 3;	} else {		stype = "zdefault";		uri = _service_str;	}	if (!z_master_server_test_mode) {		p = strchr(uri, ':');		if (p == 0) {			zlog_fatal("%s: args error: %s", zvar_program_name, service_str);		}		*p = 0;		type = *uri;		sock_fd = atoi(p + 1);	} else {		char *host_path;		int port;		___ziuf_parse(uri, type, host_path, port);		if (type == ZSOCKET_TYPE_INET) {			sock_fd = zsocket_inet_listen(host_path, port, -1);		} else if (type == ZSOCKET_TYPE_UNIX) {			sock_fd = zsocket_unix_listen(host_path, -1, 1, 0);		} else if (type == ZSOCKET_TYPE_FIFO) {			sock_fd = zsocket_fifo_listen(host_path, 1, 0);		} else {			sock_fd = -1;			zlog_fatal("%s: args error: %s", zvar_program_name, service_str);		}		if (sock_fd < 0) {			zlog_fatal("%s: open: %s error (%m)", zvar_program_name, service_str);		}	}	service = zmaster_server_register_find_service(service_list, stype);	if (service->raw_flag) {		if (service->callback) {			service->callback(sock_fd, service->ctx, type);		}		return;	}	a_c = (___ACCEPT_CONTEXT *) zmalloc(sizeof(___ACCEPT_CONTEXT));	a_c->callback = service->callback;	a_c->type = type;	a_c->ctx = service->ctx;	zio_close_on_exec(sock_fd, 1);	zio_nonblocking(sock_fd, 1);	zev = (ZEVENT *) zmalloc(sizeof(ZEVENT));	zevent_init(zev, zvar_default_event_base, sock_fd);	zevent_set(zev, ZEVENT_READ, zmaster_server_accept, a_c, 0);	zarray_enter(z_master_server_listen_fd_list, ZINT_TO_VOID_PTR(sock_fd));}
开发者ID:mailhonor,项目名称:libzc,代码行数:70,


示例28: zmailer_msg_new

zmailer_msg_t *zmailer_msg_new (void){    zmailer_msg_t *self = (zmailer_msg_t *) zmalloc (sizeof (zmailer_msg_t));    return self;}
开发者ID:oikosdev,项目名称:zmailer,代码行数:6,


示例29: zmsg_test

//.........这里部分代码省略.........    assert (zmsg_content_size (msg) == 60);    //  Remove all frames except first and last    int frame_nbr;    for (frame_nbr = 0; frame_nbr < 8; frame_nbr++) {        zmsg_first (msg);        frame = zmsg_next (msg);        zmsg_remove (msg, frame);        zframe_destroy (&frame);    }    //  Test message frame manipulation    assert (zmsg_size (msg) == 2);    frame = zmsg_last (msg);    assert (zframe_streq (frame, "Frame9"));    assert (zmsg_content_size (msg) == 12);    frame = zframe_new ("Address", 7);    assert (frame);    zmsg_prepend (msg, &frame);    assert (zmsg_size (msg) == 3);    rc = zmsg_addstr (msg, "Body");    assert (rc == 0);    assert (zmsg_size (msg) == 4);    frame = zmsg_pop (msg);    zframe_destroy (&frame);    assert (zmsg_size (msg) == 3);    char *body = zmsg_popstr (msg);    assert (streq (body, "Frame0"));    free (body);    zmsg_destroy (&msg);    //  Test encoding/decoding    msg = zmsg_new ();    assert (msg);    byte *blank = (byte *) zmalloc (100000);    assert (blank);    rc = zmsg_addmem (msg, blank, 0);    assert (rc == 0);    rc = zmsg_addmem (msg, blank, 1);    assert (rc == 0);    rc = zmsg_addmem (msg, blank, 253);    assert (rc == 0);    rc = zmsg_addmem (msg, blank, 254);    assert (rc == 0);    rc = zmsg_addmem (msg, blank, 255);    assert (rc == 0);    rc = zmsg_addmem (msg, blank, 256);    assert (rc == 0);    rc = zmsg_addmem (msg, blank, 65535);    assert (rc == 0);    rc = zmsg_addmem (msg, blank, 65536);    assert (rc == 0);    rc = zmsg_addmem (msg, blank, 65537);    assert (rc == 0);    free (blank);    assert (zmsg_size (msg) == 9);    byte *buffer;    size_t buffer_size = zmsg_encode (msg, &buffer);    zmsg_destroy (&msg);    msg = zmsg_decode (buffer, buffer_size);    assert (msg);    free (buffer);    zmsg_destroy (&msg);    //  Test submessages    msg = zmsg_new ();    assert (msg);
开发者ID:dadavita,项目名称:stalk,代码行数:67,


示例30: yylex

//.........这里部分代码省略.........		}		yylval.cp = field_ptr(ival);	    }	    ct_ret(FIELD);	}    case SC_DQUOTE:	return current_token = collect_string();    case SC_IDCHAR:		/* collect an identifier */	{	    char *p = string_buff + 1;	    SYMTAB *stp;	    string_buff[0] = (char) c;	    while (1) {		CheckStringSize(p);		c = scan_code[NextUChar(*p++)];		if (c != SC_IDCHAR && c != SC_DIGIT)		    break;	    }	    un_next();	    *--p = 0;	    switch ((stp = find(string_buff))->type) {	    case ST_NONE:		/* check for function call before defined */		if (next() == '(') {		    stp->type = ST_FUNCT;		    stp->stval.fbp = (FBLOCK *)			zmalloc(sizeof(FBLOCK));		    stp->stval.fbp->name = stp->name;		    stp->stval.fbp->code = (INST *) 0;		    stp->stval.fbp->size = 0;		    yylval.fbp = stp->stval.fbp;		    current_token = FUNCT_ID;		} else {		    yylval.stp = stp;		    current_token =			current_token == DOLLAR ? D_ID : ID;		}		un_next();		break;	    case ST_NR:		NR_flag = 1;		stp->type = ST_VAR;		/* FALLTHRU */	    case ST_VAR:	    case ST_ARRAY:	    case ST_LOCAL_NONE:	    case ST_LOCAL_VAR:	    case ST_LOCAL_ARRAY:		yylval.stp = stp;		current_token =		    current_token == DOLLAR ? D_ID : ID;		break;	    case ST_ENV:		stp->type = ST_ARRAY;		stp->stval.array = new_ARRAY();
开发者ID:ThomasDickey,项目名称:mawk-snapshots,代码行数:67,



注:本文中的zmalloc函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


C++ zmalloc_size函数代码示例
C++ zlog_warn函数代码示例
万事OK自学网:51自学网_软件自学网_CAD自学网自学excel、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。