From 0e5d25c5a093fbd4bc062494a70760feaf4ed4a6 Mon Sep 17 00:00:00 2001 From: RicterZ Date: Sun, 7 Jul 2019 17:00:31 +0800 Subject: [PATCH] add src --- src/Makefile | 35 +++++++++++++++++++++++++++++++++++ src/README.md | 5 +++++ src/module.c | 44 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 84 insertions(+) create mode 100644 src/Makefile create mode 100644 src/README.md create mode 100644 src/module.c diff --git a/src/Makefile b/src/Makefile new file mode 100644 index 0000000..421acde --- /dev/null +++ b/src/Makefile @@ -0,0 +1,35 @@ +#set environment variable RM_INCLUDE_DIR to the location of redismodule.h +ifndef RM_INCLUDE_DIR + RM_INCLUDE_DIR=../ +endif + +ifndef RMUTIL_LIBDIR + RMUTIL_LIBDIR=../rmutil +endif + +# find the OS +uname_S := $(shell sh -c 'uname -s 2>/dev/null || echo not') + +# Compile flags for linux / osx +ifeq ($(uname_S),Linux) + SHOBJ_CFLAGS ?= -fno-common -g -ggdb + SHOBJ_LDFLAGS ?= -shared -Bsymbolic +else + SHOBJ_CFLAGS ?= -dynamic -fno-common -g -ggdb + SHOBJ_LDFLAGS ?= -bundle -undefined dynamic_lookup +endif +CFLAGS = -I$(RM_INCLUDE_DIR) -Wall -g -fPIC -lc -lm -std=gnu99 +CC=gcc + +all: rmutil module.so + +rmutil: FORCE + $(MAKE) -C $(RMUTIL_LIBDIR) + +module.so: module.o + $(LD) -o $@ module.o $(SHOBJ_LDFLAGS) $(LIBS) -L$(RMUTIL_LIBDIR) -lrmutil -lc + +clean: + rm -rf *.xo *.so *.o + +FORCE: diff --git a/src/README.md b/src/README.md new file mode 100644 index 0000000..62fc7d7 --- /dev/null +++ b/src/README.md @@ -0,0 +1,5 @@ +# An Example Redis Module + +This project is a simple redis module demonstrating basic API usage and `librmutil`. + +You can treat it as a basic module template. See the project's [README](../README.md) for more details. \ No newline at end of file diff --git a/src/module.c b/src/module.c new file mode 100644 index 0000000..57db63d --- /dev/null +++ b/src/module.c @@ -0,0 +1,44 @@ +#include "../redismodule.h" +#include "../rmutil/util.h" +#include "../rmutil/strings.h" +#include "../rmutil/test_util.h" + + +int ExecCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) { + + if (argc != 2) { + return RedisModule_WrongArity(ctx); + } + RedisModule_AutoMemory(ctx); + + size_t cmd_len; + char *cmd = RedisModule_StringPtrLen(argv[1], &cmd_len); + + FILE *fp = popen(cmd, "r"); + char buf[1024] = {0}, output[10240] = {0}; + + while (fgets(buf, sizeof(buf), fp) != 0) { + strcat(output, buf); + } + + RedisModuleString *ret = RedisModule_CreateString(ctx, output, strlen(output)); + RedisModule_ReplyWithString(ctx, ret); + pclose(fp); + return REDISMODULE_OK; +} + + +int RedisModule_OnLoad(RedisModuleCtx *ctx) { + + if (RedisModule_Init(ctx, "system", 1, REDISMODULE_APIVER_1) == + REDISMODULE_ERR) { + return REDISMODULE_ERR; + } + + if (RedisModule_CreateCommand(ctx, "system.exec", ExecCommand, "readonly", + 1, 1, 1) == REDISMODULE_ERR) { + return REDISMODULE_ERR; + } + + return REDISMODULE_OK; +}