Skip to content

Instantly share code, notes, and snippets.

@badboy
Last active September 3, 2017 03:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save badboy/c956c30ef77e904181c3c7efc9a503a1 to your computer and use it in GitHub Desktop.
Save badboy/c956c30ef77e904181c3c7efc9a503a1 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <hiredis.h>
int main(int argc, char **argv) {
redisContext *c;
redisReply *reply;
const char *hostname = (argc > 1) ? argv[1] : "127.0.0.1";
int port = (argc > 2) ? atoi(argv[2]) : 6379;
struct timeval timeout = { 1, 500000 }; // 1.5 seconds
c = redisConnectWithTimeout(hostname, port, timeout);
if (c == NULL || c->err) {
if (c) {
printf("Connection error: %s\n", c->errstr);
redisFree(c);
} else {
printf("Connection error: can't allocate redis context\n");
}
exit(1);
}
const char *key = "D11BA97064C28242739B7A5E06A3887B";
const char *fields[] = {
"content",
"href",
};
const char *values[] = {
"a plus b",
"just_test",
};
// command + key + 2 * (number of field/value pairs)
int argcount = 1 + 1 + 2 * 2;
char **args = malloc(argcount * sizeof(char*));
size_t *argvlen = malloc(argcount * sizeof(size_t));
args[0] = malloc(strlen("HMSET"));
argvlen[0] = strlen("HMSET");
memcpy(args[0], "HMSET", strlen("HMSET"));
args[1] = malloc(strlen(key));
argvlen[1] = strlen(key);
memcpy(args[1], key, strlen(key));
for (int i=0; i<2; i++) {
int argsidx = 2 + (i*2);
args[argsidx] = malloc(strlen(fields[i]) * sizeof(char));
args[argsidx+1] = malloc(strlen(values[i]) * sizeof(char));
memcpy(args[argsidx], fields[i], strlen(fields[i]));
memcpy(args[argsidx+1], values[i], strlen(values[i]));
argvlen[argsidx] = strlen(fields[i]);
argvlen[argsidx+1] = strlen(values[i]);
}
reply = redisCommandArgv(c, argcount, (const char**)args, argvlen);
freeReplyObject(reply);
/* Disconnects and frees the context */
redisFree(c);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment