#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/stat.h>
#define MAXLINE 100
static void do_exit(const char *s);
int main(){
int r, m, i, j;
int childstatus;
//printf("입력할 숫자의 개수: ");
//scanf("%d", &n);
//if(!n) do_exit("n value null");
//int *num = malloc(sizeof(int) * n);
//if(!num) do_eixt("malloc error");
//for(i=0; i<n; i++){
// scanf("%d", &num[i]);
//}
printf("프로세스 개수(1~10): ");
scanf("%d", &m);
if(m<1 || m>10) do_exit("m range over");
pid_t pid[m];
for(i=0; i<m; i++){
int fd1[2], fd2[2];
if(pipe(fd1) < 0) do_exit("pipe error");
if(pipe(fd2) < 0) do_exit("pipe error");
pid[i] = fork();
if(pid[i] < 0){
do_exit("fork error");
} else if(pid[i] == 0){
char getnum[MAXLINE];
close(fd1[1]);
if((r = read(fd1[0], getnum, MAXLINE)) > 0);
//printf("get num: %s\n", getnum);
close(fd1[0]);
int childsum = 0, cnt = 0;
char *arr = strtok(getnum, " ");
int setsum[MAXLINE];
while(arr != NULL){
setsum[cnt] = atoi(arr);
cnt++;
//printf("arr: %s\n", arr);
arr = strtok(NULL, " ");
}
//printf("strlen :%d\n", cnt);
for(j=i*cnt/m; j<(i+1)*cnt/m;j++){
printf("\ni: %d, m: %d, cnt: %d, %d, %d\n", i, m, cnt, i*cnt/m, (i+1)*cnt/m);
childsum += setsum[i];
}
write(fd2[1], (char *)&childsum, sizeof childsum);
printf("csum: %d\n", childsum);
//printf("\ni: %d, m: %d, n: %d, %d, %d\n", i, m, n, i*n/m, (i+1)*n/m);
//printf("child: , %d\n\n", (int)getpid());
exit(0);
} else{
int sum = 0, n;
//printf("parent: %d - child: %d\n\n", (int)getpid() , (int)pid[i]);
close(fd1[0]);
close(fd2[1]);
printf("입력할 숫자의 개수: ");
scanf("%d", &n);
if(!n) do_exit("n value null");
int *num = malloc(MAXLINE);
if(!num) do_exit("malloc error");
char *setnum = malloc(MAXLINE);
if(!setnum) do_exit("malloc error");
for(i=0; i<n; i++){
scanf("%d", &num[i]);
char tmp[MAXLINE];
sprintf(tmp, "%d", num[i]);
strcat(setnum, tmp);
strcat(setnum, " ");
}
write(fd1[1], setnum, MAXLINE);
pid_t cstatus = wait(&childstatus);
int r;
char getsum[MAXLINE];
struct stat st;
if(fstat(fd2[0], &st) < 0) do_exit("stat error");
if(st.st_size > MAXLINE) do_exit("fd[0] len error");
while((r = read(fd2[0], getsum, MAXLINE)) > 0){
printf("\nchild sum: %s\n", getsum);
sum+= atoi(getsum);
}
close(fd2[0]);
printf("parent sum: %d\n", sum);
if(WIFEXITED(childstatus)){
printf("exit, status=%d\n", WEXITSTATUS(childstatus));
}else{
printf("abnormal exit\n");
}
}
}