Redis源码分析(二)redis-cli.c

文章目录

    • 1. int main()
    • 2. parseOptions(int argc, char **argv) 进行ip和port的改变
    • 3. lookupCommand(char *name) 查找命令,判断命令合法
    • 3.2 strcasecmp(name,cmdTable[j].name)
    • 3.1 redisCommand cmdTable[]
    • 4. cliSendCommand(int argc, char **argv)
    • 4.1 cliConnect(void)
    • 8.1 9.1 cliReadLine(int fd)
    • 8 cliReadSingleLineReply(int fd)
    • 9 cliReadBulkReply(int fd)
    • cliReadMultiBulkReply(int fd)
    • cliReadReply(int fd)
    • readArgFromStdin(void)

1. int main()

int main(int argc, char **argv) {int firstarg, j;char **argvcopy;struct redisCommand *rc;config.hostip = "127.0.0.1";config.hostport = 6379;firstarg = parseOptions(argc,argv);argc -= firstarg;argv += firstarg;/* Turn the plain C strings into Sds strings */argvcopy = zmalloc(sizeof(char*)*argc+1);for(j = 0; j < argc; j++)argvcopy[j] = sdsnew(argv[j]);if (argc < 1) {fprintf(stderr, "usage: redis-cli [-h host] [-p port] cmd arg1 arg2 arg3 ... argN\n");fprintf(stderr, "usage: echo \"argN\" | redis-cli [-h host] [-p port] cmd arg1 arg2 ... arg(N-1)\n");fprintf(stderr, "\nIf a pipe from standard input is detected this data is used as last argument.\n\n");fprintf(stderr, "example: cat /etc/passwd | redis-cli set my_passwd\n");fprintf(stderr, "example: redis-cli get my_passwd\n");exit(1);}/* Read the last argument from stdandard input if needed */if ((rc = lookupCommand(argv[0])) != NULL) {if (rc->arity > 0 && argc == rc->arity-1) {sds lastarg = readArgFromStdin();argvcopy[argc] = lastarg;argc++;}}return cliSendCommand(argc, argvcopy);
}

2. parseOptions(int argc, char **argv) 进行ip和port的改变

static int parseOptions(int argc, char **argv) {int i;for (i = 1; i < argc; i++) {int lastarg = i==argc-1;if (!strcmp(argv[i],"-h") && !lastarg) {char *ip = zmalloc(32);if (anetResolve(NULL,argv[i+1],ip) == ANET_ERR) {printf("Can't resolve %s\n", argv[i]);exit(1);}config.hostip = ip;i++;} else if (!strcmp(argv[i],"-p") && !lastarg) {config.hostport = atoi(argv[i+1]);i++;} else {break;}}return i;
}

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>#include "anet.h"
#include "sds.h"
#include "adlist.h"
#include "zmalloc.h"#define REDIS_CMD_INLINE 1
#define REDIS_CMD_BULK 2#define REDIS_NOTUSED(V) ((void) V)static struct config {char *hostip;int hostport;
} config;struct redisCommand {char *name;int arity;int flags;
};

3. lookupCommand(char *name) 查找命令,判断命令合法

static struct redisCommand *lookupCommand(char *name) {int j = 0;while(cmdTable[j].name != NULL) {if (!strcasecmp(name,cmdTable[j].name)) return &cmdTable[j];j++;}return NULL;
}

3.2 strcasecmp(name,cmdTable[j].name)

后面的版本把这个比较进行了处理,如SeT,GET等

3.1 redisCommand cmdTable[]

static struct redisCommand cmdTable[] = {{"get",2,REDIS_CMD_INLINE},{"set",3,REDIS_CMD_BULK},{"setnx",3,REDIS_CMD_BULK},{"del",-2,REDIS_CMD_INLINE},{"exists",2,REDIS_CMD_INLINE},{"incr",2,REDIS_CMD_INLINE},{"decr",2,REDIS_CMD_INLINE},{"rpush",3,REDIS_CMD_BULK},{"lpush",3,REDIS_CMD_BULK},{"rpop",2,REDIS_CMD_INLINE},{"lpop",2,REDIS_CMD_INLINE},{"llen",2,REDIS_CMD_INLINE},{"lindex",3,REDIS_CMD_INLINE},{"lset",4,REDIS_CMD_BULK},{"lrange",4,REDIS_CMD_INLINE},{"ltrim",4,REDIS_CMD_INLINE},{"lrem",4,REDIS_CMD_BULK},{"sadd",3,REDIS_CMD_BULK},{"srem",3,REDIS_CMD_BULK},{"smove",4,REDIS_CMD_BULK},{"sismember",3,REDIS_CMD_BULK},{"scard",2,REDIS_CMD_INLINE},{"spop",2,REDIS_CMD_INLINE},{"sinter",-2,REDIS_CMD_INLINE},{"sinterstore",-3,REDIS_CMD_INLINE},{"sunion",-2,REDIS_CMD_INLINE},{"sunionstore",-3,REDIS_CMD_INLINE},{"sdiff",-2,REDIS_CMD_INLINE},{"sdiffstore",-3,REDIS_CMD_INLINE},{"smembers",2,REDIS_CMD_INLINE},{"incrby",3,REDIS_CMD_INLINE},{"decrby",3,REDIS_CMD_INLINE},{"getset",3,REDIS_CMD_BULK},{"randomkey",1,REDIS_CMD_INLINE},{"select",2,REDIS_CMD_INLINE},{"move",3,REDIS_CMD_INLINE},{"rename",3,REDIS_CMD_INLINE},{"renamenx",3,REDIS_CMD_INLINE},{"keys",2,REDIS_CMD_INLINE},{"dbsize",1,REDIS_CMD_INLINE},{"ping",1,REDIS_CMD_INLINE},{"echo",2,REDIS_CMD_BULK},{"save",1,REDIS_CMD_INLINE},{"bgsave",1,REDIS_CMD_INLINE},{"shutdown",1,REDIS_CMD_INLINE},{"lastsave",1,REDIS_CMD_INLINE},{"type",2,REDIS_CMD_INLINE},{"flushdb",1,REDIS_CMD_INLINE},{"flushall",1,REDIS_CMD_INLINE},{"sort",-2,REDIS_CMD_INLINE},{"info",1,REDIS_CMD_INLINE},{"mget",-2,REDIS_CMD_INLINE},{"expire",3,REDIS_CMD_INLINE},{"ttl",2,REDIS_CMD_INLINE},{"slaveof",3,REDIS_CMD_INLINE},{"debug",-2,REDIS_CMD_INLINE},{NULL,0,0}
};
static int cliReadReply(int fd);

4. cliSendCommand(int argc, char **argv)

static int cliSendCommand(int argc, char **argv) {struct redisCommand *rc = lookupCommand(argv[0]);int fd, j, retval = 0;sds cmd = sdsempty();if (!rc) {fprintf(stderr,"Unknown command '%s'\n",argv[0]);return 1;}if ((rc->arity > 0 && argc != rc->arity) ||(rc->arity < 0 && argc < -rc->arity)) {fprintf(stderr,"Wrong cliConnect of arguments for '%s'\n",rc->name);return 1;}if ((fd = cliConnect()) == -1) return 1;/* Build the command to send */for (j = 0; j < argc; j++) {if (j != 0) cmd = sdscat(cmd," ");if (j == argc-1 && rc->flags & REDIS_CMD_BULK) {cmd = sdscatprintf(cmd,"%d",sdslen(argv[j]));} else {cmd = sdscatlen(cmd,argv[j],sdslen(argv[j]));}}cmd = sdscat(cmd,"\r\n");if (rc->flags & REDIS_CMD_BULK) {cmd = sdscatlen(cmd,argv[argc-1],sdslen(argv[argc-1]));cmd = sdscat(cmd,"\r\n");}anetWrite(fd,cmd,sdslen(cmd));retval = cliReadReply(fd);if (retval) {close(fd);return retval;}close(fd);return 0;
}

4.1 cliConnect(void)

static int cliConnect(void) {char err[ANET_ERR_LEN];int fd;fd = anetTcpConnect(err,config.hostip,config.hostport);if (fd == ANET_ERR) {fprintf(stderr,"Connect: %s\n",err);return -1;}anetTcpNoDelay(NULL,fd);return fd;
}

8.1 9.1 cliReadLine(int fd)

static sds cliReadLine(int fd) {sds line = sdsempty();while(1) {char c;ssize_t ret;ret = read(fd,&c,1);if (ret == -1) {sdsfree(line);return NULL;} else if ((ret == 0) || (c == '\n')) {break;} else {line = sdscatlen(line,&c,1);}}return sdstrim(line,"\r\n");
}

8 cliReadSingleLineReply(int fd)

static int cliReadSingleLineReply(int fd) {sds reply = cliReadLine(fd);if (reply == NULL) return 1;printf("%s\n", reply);return 0;
}

9 cliReadBulkReply(int fd)

static int cliReadBulkReply(int fd) {sds replylen = cliReadLine(fd);char *reply, crlf[2];int bulklen;if (replylen == NULL) return 1;bulklen = atoi(replylen);if (bulklen == -1) {sdsfree(replylen);printf("(nil)");return 0;}reply = zmalloc(bulklen);anetRead(fd,reply,bulklen);anetRead(fd,crlf,2);if (bulklen && fwrite(reply,bulklen,1,stdout) == 0) {zfree(reply);return 1;}if (isatty(fileno(stdout)) && reply[bulklen-1] != '\n')printf("\n");zfree(reply);return 0;
}

cliReadMultiBulkReply(int fd)

static int cliReadMultiBulkReply(int fd) {sds replylen = cliReadLine(fd);int elements, c = 1;if (replylen == NULL) return 1;elements = atoi(replylen);if (elements == -1) {sdsfree(replylen);printf("(nil)\n");return 0;}if (elements == 0) {printf("(empty list or set)\n");}while(elements--) {printf("%d. ", c);if (cliReadReply(fd)) return 1;c++;}return 0;
}

cliReadReply(int fd)

static int cliReadReply(int fd) {char type;if (anetRead(fd,&type,1) <= 0) exit(1);switch(type) {case '-':printf("(error) ");cliReadSingleLineReply(fd);return 1;case '+':case ':':return cliReadSingleLineReply(fd);case '$':return cliReadBulkReply(fd);case '*':return cliReadMultiBulkReply(fd);default:printf("protocol error, got '%c' as reply type byte\n", type);return 1;}
}

readArgFromStdin(void)

static sds readArgFromStdin(void) {char buf[1024];sds arg = sdsempty();while(1) {int nread = read(fileno(stdin),buf,1024);if (nread == 0) break;else if (nread == -1) {perror("Reading from standard input");exit(1);}arg = sdscatlen(arg,buf,nread);}return arg;
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/382375.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

C语言中有bool变量吗?

1.C/C中定义的数据类型&#xff1a; C语言中定义了6种基本数据类型&#xff1a;short,int,long,float,double,char 4种构造类型&#xff1a;数组&#xff0c;结构体&#xff08;struct&#xff09;&#xff0c;共用类型(union)&#xff0c;枚举类型(enum) 指针类型和空类型 C语…

redis源码剖析(三)——基础数据结构

文章目录SDS链表字典这篇文章关于 Redis 的基础数据:SDS SDS &#xff08;Simple Dynamic String&#xff09;是 Redis 最基础的数据结构。直译过来就是”简单的动态字符串“。Redis 自己实现了一个动态的字符串&#xff0c;而不是直接使用了 C 语言中的字符串。 sds 的数据结…

C++迭代器使用错误总结

指针和迭代器的区别&#xff1a; 迭代器&#xff1a; &#xff08;1&#xff09;迭代器不是指针&#xff0c;是类模板&#xff0c;表现的像指针。他只是模拟了指针的一些功能&#xff0c;通过重载了指针的一些操作符&#xff0c;->,*, --等封装了指针&#xff0c;是一…

redis源码剖析(四)跳表

文章目录整数集合跳跃表压缩列表总结整数集合 当一个集合只包含整数&#xff0c;且这个集合的元素不多的时候&#xff0c;Redis 就会使用整数集合 intset 。首先看 intset 的数据结构&#xff1a; typedef struct intset {// 编码方式uint32_t encoding;// 集合包含的元素数量…

vivo C/C++工程师 HR视频面试问题总结20180807

一开始没想到这次视频面是HR面试&#xff0c;还以为是技术面试&#xff0c;毕竟上次面试的时候技术问题问的相对比较少&#xff0c;所以面试准备方向有点儿错了&#xff0c;不过还是总结一下具体问题。 1&#xff09;自我介绍&#xff1a;吸取了上次自我介绍的经验&#xff0c;…

在Redis客户端设置连接密码 并演示密码登录

我们先连接到Redis服务 然后 我们要输入 CONFIG SET requirepass “新密码” 例如 CONFIG SET requirepass "A15167"这样 密码就被设置成立 A15167 我们 输入 AUTH 密码 例如 AUTH A15167这里 返回OK说明成功了 然后 我们退出在登录就真的需要 redis-cli -h IP地…

redis源码剖析(五)—— 字符串,列表,哈希,集合,有序集合

文章目录对象REDIS_STRING &#xff08;字符串&#xff09;REDIS_LIST 列表REDIS_SET &#xff08;集合&#xff09;REDIS_ZSET &#xff08;有序集合&#xff09;REDIS_HASH (hash表)int refcount&#xff08;引用计数器&#xff09;unsigned lru:REDIS_LRU_BITS对象 对于 Re…

函数sscanf小结

1.sscanf用于处理固定格式的字符串&#xff0c;包含在头文件<cstdio>中&#xff0c;函数原型为&#xff1a; int sscanf(const char *buffer,const char*format,[]argument ]...); 其中:buffer代表着要存储的数据&#xff0c;format 代表格式控制字符串&#xff0c;arg…

redis源码剖析(六)—— Redis 数据库、键过期的实现

文章目录数据库的实现数据库读写操作键的过期实现数据库的实现 我们先看代码 server.h/redisServer struct redisServer{...//保存 db 的数组redisDb *db;//db 的数量int dbnum;... }再看redisDb的代码&#xff1a; typedef struct redisDb {dict *dict; /*…

多益网络 视频面试面试总结20180816

1.首先是自我介绍&#xff1a;因为等了半个小时&#xff0c;所以有点儿紧张&#xff0c;只说了一下自己的学校&#xff0c;爱好和兴趣&#xff1b; 2.介绍了一个自己的最成功的项目&#xff1a;我介绍了一个关于GPS导航的项目&#xff0c;介绍了项目的内容和项目的一些工作&am…

redis源码剖析(七)—— Redis 数据结构dict.c

文章目录dict.hdict.cdict.h //定义错误相关的码 #define DICT_OK 0 #define DICT_ERR 1//实际存放数据的地方 typedef struct dictEntry {void *key;void *val;struct dictEntry *next; } dictEntry;//哈希表的定义 typedef struct dict {//指向实际的哈希表记录(用数组开链的…

简述linux中动态库和静态库的制作调用流程

假设现在有这些文件&#xff1a;sub.c add.c div.c mul.c mainc head.h&#xff08;前4个.C文件的头文件&#xff09; 1.静态库制作流程 gcc -c sub.c add.c div.c mul.c -->生成 .o目标文件文件 ar rcs libmycal.a *.o …

redis源码剖析(八)—— 当你启动Redis的时候,Redis做了什么

文章目录启动过程初始化server结构体main函数会调用initServer函数初始化服务器状态载入持久化文件&#xff0c;还原数据库开始监听事件流程图启动过程 初始化server结构体从配置文件夹在加载参数初始化服务器载入持久化文件开始监听事件 初始化server结构体 服务器的运行ID…

linux中错误总结归纳

1.使用gcc编译C文件&#xff0c;C文件在for循环语句中出现变量定义 编译器提示错误&#xff1a;“for”loop initial declarations are only allowed in C99 mode. note:use option -stdc99or-stdgnu99 to compile; 原因&#xff1a;gcc的标准是基于c89的&#xff0c;c89不能在…

redis源码剖析(十一)—— Redis字符串相关函数实现

文章目录初始化字符串字符串基本操作字符串拼接操作other获取指定范围里的字符串将字符串中的所有字符均转为小写的形式将字符串中所有字符均转为大写的形式字符串比较other#define SDS_ABORT_ON_OOM#include "sds.h" #include <stdio.h> #include <stdlib.…

makefile内容小结

makefile中每个功能主要分为三部分&#xff1a;目标&#xff0c;依赖条件和命令语句 1.支持对比更新的Makefile写法&#xff08;只会编译文件时.o文件和.c文件时间不一致的文件&#xff09; 2.使用makefile自动变量和自定义变量的makefile写法 其中&#xff1a;这三个符号为ma…

事务隔离级别动图演示

事务的基本要素&#xff08;ACID&#xff09; 原子性&#xff08;Atomicity&#xff09; 事务开始后所有操作&#xff0c;要么全部做完&#xff0c;要么全部不做&#xff0c;不可能停滞在中间环节。事务执行过程中出错&#xff0c;会回滚到事务开始前的状态&#xff0c;所有的…

C/C++的优点和缺点

1.C/C语言的优点 C语言是面向过程的语言&#xff0c;常用来编写操作系统。C语言是从C语言发展过来的&#xff0c;是一门面向对象的语言&#xff0c;它继承了C语言的优势&#xff0c;同时也添加了三个主要的内容&#xff1a;Oriented-Object class,Template,STL. 1)C/C可以潜入…

C/C++命令行参数那点事

int main(int argc, char *argv[ ]); 1.命令行参数&#xff1a;在命令行中给定的参数&#xff1b; 2.命令行参数在对函数main的调用时&#xff0c;主要有两个参数送到main,一个是argc(argument count),命令行参数的个数&#xff0c;另外一个是argv,命令行参数的数组,命令行参…

mysql row_id为什么是6字节?为什么是8字节

mysql row_id是几个字节&#xff1f; row_id InnoDB表中在没有默认主键的情况下会生成一个6字节空间的自动增长主键 row_id是整型还是字符型&#xff1f; 源代码中 row_id 是 ib_uint64_t 这是 8字节 uint64_t 是整形 为什么是6个字节&#xff1f; P.S. Base64编码说明 B…