歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Hadoop 上使用C 語言編程

Hadoop 上使用C 語言編程

日期:2017/3/1 10:24:16   编辑:Linux編程

今天嘗試用C語言在Hadoop上編寫統計單詞的程序,具體過程如下:

一、編寫map和reduce程序

mapper.c

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #define BUF_SIZE 2048
  5. #define DELIM '\n'
  6. int main(int argc, char * argv[])
  7. {
  8. char buffer[BUF_SIZE];
  9. while(fgets(buffer,BUF_SIZE-1,stdin))
  10. {
  11. int len = strlen(buffer);
  12. if(buffer[len-1] == DELIM) // 將換行符去掉
  13. buffer[len-1] = 0;
  14. char *query = NULL;
  15. query = strtok(buffer, " ");
  16. while(query)
  17. {
  18. printf("%s\t1\n",query);
  19. query = strtok(NULL," ");
  20. }
  21. }
  22. return 0;
  23. }
reducer.c
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #define BUFFER_SIZE 1024
  5. #define DELIM "\t"
  6. int main(int argc, char * argv[])
  7. {
  8. char str_last_key[BUFFER_SIZE];
  9. char str_line[BUFFER_SIZE];
  10. int count = 0;
  11. *str_last_key = '\0';
  12. while( fgets(str_line,BUFFER_SIZE-1,stdin) )
  13. {
  14. char * str_cur_key = NULL;
  15. char * str_cur_num = NULL;
  16. str_cur_key = strtok(str_line,DELIM);
  17. str_cur_num = strtok(NULL,DELIM);
  18. if(str_last_key[0] =='\0')
  19. {
  20. strcpy(str_last_key,str_cur_key);
  21. }
  22. if(strcmp(str_cur_key, str_last_key))// 前後不相等,輸出
  23. {
  24. printf("%s\t%d\n",str_last_key,count);
  25. count = atoi(str_cur_num);
  26. }else{// 相等,則加當前的key的value
  27. count += atoi(str_cur_num);
  28. }
  29. strcpy(str_last_key,str_cur_key);
  30. }
  31. printf("%s\t%d\n",str_last_key,count);
  32. return 0;
  33. }
二、編譯

gcc mapper.c -o mapper

gcc reducer.c -o reducer

三、運行

(一)啟動hadoop後將待統計單詞的輸入文件放到 input文件夾中:bin/hadoop fs -put 待統計文件 input

(二)使用contrib/streaming/下的jar工具調用上面的mapper\reducer:

bin/hadoop jar /home/huangkq/Desktop/hadoop/contrib/streaming/hadoop-streaming-0.20.203.0.jar -mapper /home/huangkq/Desktop/hadoop2/mapper -reducer /home/huangkq/Desktop/hadoop2/reducer -input input -output c_output -jobconf mapred.reduce.tasks=2

說明:hadoop-streaming-0.20.203.0.jar是一個管道工具

(三)查看結果:bin/hadoop fs -cat c_output/*

更多Hadoop相關信息見Hadoop 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=13

Copyright © Linux教程網 All Rights Reserved