Chinaunix首页 | 论坛 | 博客
  • 博客访问: 94628
  • 博文数量: 25
  • 博客积分: 10
  • 博客等级: 民兵
  • 技术积分: 316
  • 用 户 组: 普通用户
  • 注册时间: 2012-08-02 00:39
文章分类

全部博文(25)

文章存档

2013年(25)

我的朋友

分类: 架构设计与优化

2013-04-22 17:06:05

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include


struct args{
    char filename[BUFSIZ];
    char fileno[8];
};

void * func(void *arg)
{
    struct args *arglist=(struct args *)arg;
    strcat(arglist->filename,arglist->fileno);    

    redisContext *c=redisConnectUnix("/tmp/redis.sock");
    if(c->err){
        fprintf(stderr,"thread_id:%x can't connect to redis server and exit\n",pthread_self());
        return ;
    }

    FILE *fp=fopen(arglist->filename,"r");
    if(!fp){
        fprintf(stderr,"can't open file %s and exit\n",arglist->filename);
        return ;
    }

    char buf[BUFSIZ];
    struct columns{
        char col1[BUFSIZ];
        char col2[BUFSIZ];
    }columns;

    redisReply *reply;
    unsigned long long errop = 0;
    while(fgets(buf,BUFSIZ,fp)!=NULL){
        sscanf(buf,"%s\t%s",columns.col1,columns.col2);
        reply=redisCommand(c,"set %s %s",columns.col1,columns.col2);
        if(strcmp(reply->str,"OK"))
            errop++;
        freeReplyObject(reply);
    }
    /* maybe safe free?*/
    free(arglist);
}

int main(int ac, char **av)
{
    setbuf(stderr,NULL);

    if(ac!=3){
        fprintf(stderr,"usage:./redis_load \n");
        return 1;
    }
    
    long int n = strtol(av[2],(char **)NULL,10);

    if ((errno = ERANGE && (n==LONG_MAX || n ==LONG_MIN)) || (errno !=0 && n ==0)){
        fprintf(stderr," is not a long int\n");
        return 1;
    }

    if(strlen(av[1])>BUFSIZ-n-1){
        fprintf(stderr,"filename too long\n");
        return 1;
    }
    
    /* begin to spawn threads,first adjust the stack size per thread */
    struct rlimit limit={RLIM_INFINITY,RLIM_INFINITY};
    if(setrlimit(RLIMIT_STACK,&limit) == -1){
        fprintf(stderr,"failed to adjust the stack size,maybe the user is not root and this program will be abort to avoid segment fault\n ");
        return 1;
    }

    pthread_t tid[atoi(av[2])];
    int i;

    for(i=0;i         /*   maybe need safe malloc()? */
        struct args *args=malloc(sizeof(struct args));
        strcpy(args->filename,av[1]);
        sprintf(args->fileno,"%02d",i);
        pthread_create(tid+i,NULL,func,(void *)args);
    }

    for(i=0;i         pthread_join(tid[i],NULL);

    return 0;
}

阅读(1890) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~