Created
February 25, 2015 11:22
-
-
Save appleios/185e00d90196b9b89491 to your computer and use it in GitHub Desktop.
yandex_arm_2_proc
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <unistd.h> | |
#include <sys/types.h> | |
#include <sys/wait.h> | |
#include <stdio.h> | |
#define BATCH_SIZE 10 | |
void calc_stat_for(char *batch, int sz, int *stat){ | |
int i; | |
print_batch(batch,sz); | |
for(i=0; i<sz; i++) stat[batch[i]]++; | |
} | |
void calc(char *str, int size, int *stat, int idx) | |
{ | |
int j,l, | |
k = size/BATCH_SIZE/2; | |
for(j=0; j<k-1; j++){ | |
printf("pid=%d, processing batch: %d\n",getpid(), (j+idx)*BATCH_SIZE); | |
calc_stat_for(&str[j*BATCH_SIZE+idx],BATCH_SIZE,stat); | |
} | |
} | |
int merge_stat(int *st1, int *st2) | |
{ | |
int i,m=1; | |
for(i=2; i<256; i++) { | |
st1[i]+=st2[i]; | |
if(st1[i]>st1[m]) m = i; | |
} | |
return m; | |
} | |
char mostFrequentCharacter(char *str, int size) | |
{ | |
int stat[256] = {0}; | |
if(size > 2*BATCH_SIZE){ | |
int fd[2]; | |
pipe(fd); | |
int p = fork(); | |
if(p>0){ // calc for odd | |
close(fd[1]); | |
printf("forked parent: %d\n",getpid()); | |
calc(str, size, stat, 0); | |
int stat2[256],t; | |
read(fd[0],stat2,256*sizeof(int)); | |
wait(&t); | |
int max = merge_stat(stat, stat2); | |
print_stat(stat2); | |
return (char)max; | |
}else if(p == 0){ // calc for even | |
close(fd[0]); | |
printf("forked child: %d\n",getpid()); | |
calc(str, size, stat, 1); | |
write(fd[1],stat,256*sizeof(int)); | |
} | |
} | |
return 0; | |
} | |
int main(int argc, char *argv[]) | |
{ | |
if(argc!=2){ | |
printf("Usage: %s filename\n",argv[0]); | |
return 0; | |
} | |
FILE *f = fopen(argv[1],"r"); | |
char str[1024*1024], buf[1024]; | |
int i,k=0; | |
while (fread(buf,sizeof(char),1024,f)) { | |
for(i=0; i<1024; i++, k++) | |
str[k] = buf[i]; | |
} | |
printf("size: %d\n",k); | |
char c = mostFrequentCharacter(str, k); | |
printf("mostFrequentCharacter => %d\n", c); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment