Skip to content

Instantly share code, notes, and snippets.

@michael-grunder
Created January 2, 2023 20:37
Show Gist options
  • Save michael-grunder/22e9c821e4e47cd2d1c72f8f3550b921 to your computer and use it in GitHub Desktop.
Save michael-grunder/22e9c821e4e47cd2d1c72f8f3550b921 to your computer and use it in GitHub Desktop.
Simple hiredis example. Compile with `gcc -Wall -ocheck-hiredis check_hiredis.c -lhiredis`
#include <stdlib.h>
#include <hiredis/hiredis.h>
int main() {
redisContext *c = redisConnect("127.0.0.1", 6379);
// Short circuit if we fail to allocate a redisContext or if it
// reports an error state.
if (c == NULL || c->err) {
fprintf(stderr, "Error: Couldn't connect to Redis (%s)\n",
c && c->err ? c->errstr : "Unknown error");
exit(1);
}
printf("Connected...\n");
redisReply *reply;
// You really shouldn't need this (redisReply*) typecast in C.
reply = (redisReply*)redisCommand(c, "PING");
// Now make sure our reply is not NULL and it is a STATUS reply.
if (reply == NULL || reply->type != REDIS_REPLY_STATUS) {
fprintf(stderr, "Error: NULL or wrong type from PING!\n");
exit(1);
}
// Now you know you have a reply and it's the right type
printf("Reply: %s\n", reply->str);
// Clean up memory.
freeReplyObject(reply);
redisFree(c);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment