I am trying to create this program where pairs of integers are passed to a slave process that adds the two integers and returns the value to the Master. The Master continues to spawn slaves until all the numbers are summed into a single answer. If there are an odd number of arguments, add a 0 to the end to make it even. Here's my code. I'm not sure why its not working. If I enter 1 or 3 arguments it works fine, any other and it doesn't, any quick response would be really helpful, thanks
Code:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char *argv[])
{
int pid,i,q,z,x;
char *procpath = "/home/students/fc15105/fc1510502/Slave";
char *procname = "Slave";
int thisPid=0;
int myargc = argc-1;
int computations;
char myargs[argc];
char *mynumbers[argc];
int sumsTemp[argc];
int cc=0;
int status;
computations = myargc/2;
printf("here");
// Copy argv values into my array
for(z=0; z <= argc ;z++)
{
mynumbers[z]=argv[z+1];
}
//printf("value at argv[argc]= %s\n", argv[argc+1]);
// Continue spawning children and passing values until the numbe of computations myargc/2 <1, meaning theres only one value left, the answer
while(computations >=1 )
{
printf("\n MY CC = %i", cc);
if(cc > 0)
{
for(x=0; x < myargc;x++)
{
sprintf(myargs, "%i", sumsTemp[x]);
printf("\n %i myargs %s",x,myargs);
mynumbers[z]= myargs;
printf("\n Mynumbers[%i] = %s\n",x,mynumbers[x]);
}
}
// if Number of arguments is odd, append a 0 to the array
if( myargc % 2 != 0)
{
sprintf(myargs, "%i", 0);
mynumbers[myargc]=myargs;
myargc++;
computations = myargc/2;
}
for(q=0; q < argc; q++) // For some reason, on 2nd iteration through while loop, the values previously stored in the array mynumbers[] are gone
{
printf("\n mynumbers[%i] : %c\n",q,*mynumbers[q]);
}
printf("\n Computations : %i \n", computations); //Computations needed after check for odd argc
for(i=0; i < computations; i++)
{
pid=fork();
thisPid=pid;
if(pid== -1)
{
printf("call to fork failed, no child\n");
exit(-1);
}
if (pid == 0)
{
execl(procpath, procname,mynumbers[2*i],mynumbers[2*i+1],0);
perror("execl failed to run slave program");
exit(1);
}
else if (pid >0)
{
printf("\nParent Waiting for child # %i run throght of loop \n ",i);
wait(&status);
status = status >>8;
sumsTemp[i]=status;
printf("\n Outside loop sumsTemp[0] = %i\n",sumsTemp[0]);
printf("\n Outside loop sumsTemp[1] = %i\n",sumsTemp[1]);
printf("\n Outside loop sumsTemp[1] = %i\n",sumsTemp[2]);
printf("\n Outside loop sumsTemp[1] = %i\n",sumsTemp[3]);
}
}
for(z=0;z < myargc;z++)
{
sprintf(myargs, "%i", sumsTemp[z]);
printf("\n %i myargs %s",z,myargs);
mynumbers[z]= myargs;
printf("\n Mynumbers[%i] = %s\n",z,mynumbers[z]);
}
myargc=computations;
computations= myargc/2;
printf("\n ********************** END COMP ************************\n");
cc++;
}
printf("\nSum is %i\n",sumsTemp[0]);
for(i=0; i < argc;i++)
printf("\nmynumbers[%i]= %i\n",i,sumsTemp[i]);
}
Comment