【C/C++】c++多程式與hiredis的淺使用

風塵_NULL發表於2019-01-28

#include <iostream>
#include <hiredis/hiredis.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>

int main(){
        pid_t pid;
        pid = fork();

        if(pid <0 ){
                std::cout<< "fork error!"<<std::endl;

        }
        //父子程式都執行
        redisContext* conn = redisConnect("10.1.175.130", 6379);
        if(NULL==conn || conn->err){

                if(conn){
                        std::cout<<"Error:"<<conn->errstr<<std::endl;

                        redisFree(conn);

                } else {
                        std::cout<<"Error:Can't allocate redis context"<<std::endl;

                }

                return 0;

        }
        if(0==pid){

                const char* command = "set name yuanzaixin";
                redisReply* r = (redisReply*)redisCommand(conn, command);
                if(NULL==r){
                        redisFree(conn);
                        return 0;

                }

                std::cout<<"fork child"<<std::endl;
                freeReplyObject(r);

        }

        if(pid >0){
                //父程式執行不一樣的命令
                const char* command = "set name xinzaiyuan";
                redisReply* r = (redisReply*)redisCommand(conn, command);
                if(NULL==r){
                        redisFree(conn);
                        return 0;

                }
                std::cout<<"fork parent"<<std::endl;
                freeReplyObject(r);

        }
        //父子程式都執行
        if (NULL!=conn){

                redisFree(conn);

        }

}

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/30221425/viewspace-2565029/,如需轉載,請註明出處,否則將追究法律責任。

相關文章