1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
|
int main (int argc, char *argv[]) {
int pid, i, n, total, x, y, index, numOfArgument, num;
char *procpath = "/home/students/fc15105/fc1510513/slave";
char *procname = "slave";
if (argc > 9) {
printf("too many arguments\n");
exit(0);
}
numOfArgument = argc / 2;
if (argc % 2 == 0) {
argv[argc] = "0";
}
// the outter loop tell how many time have to go
for (index = 1, i = 1; index <= argc / 2; index++) {
x = 1; y = 2; n = 0;
// the inner loop create the childs
for (i; i <= numOfArgument; i++, x+=2, y+=2, n++) {
pid = fork(); // create
if (pid == 0) {
// each child put argument 1, 2 and then increase by 2
execl(procpath, procname, argv[x], argv[y], 0);
perror("execl failed to run slave program");
exit(1);
}
else if (pid > 0) {
wait(&total); // get the sum
num = WEXITSTATUS(total);
printf("print index of n is %d\n", n+1);
sprintf(argv[n+1], "%i", num); // store the sum in the first argument first
printf("This child PID is %d and total of this child sum is %s\n", pid, argv[n+1]);
printf("MASTER: first arguement = %s, second arguement = %s, third Arg = %s\n", argv[1], argv[2], argv[3]);
}
else {
printf("call to fork failed, no child\n");
exit(-1);
}
}
i = 1;
if (numOfArgument % 2 != 0) { // check if argument is odd add zero after. after the inner loop
argv[numOfArgument+1] = "0";
}
numOfArgument--;
}
}
|