can anyone explain to me why I am getting a segmentation fault on this code? I have been trying to figure it out and have come up empty on various searches. When I run the code without calling main(argc, argv) it runs. Slave only transforms the 2 numbers in argv to ints then returns them. Thanks.
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main(int argc, char* argv[])
{
int i;
int* sums;
sums[argc];
pid_t cpid;
int status;
char* args[10];
int count = 1;
for(i = 0; i < (argc / 2); i++) {
cpid = fork();
if(cpid == 0) {
args[1] = argv[count];
args[2] = argv[count + 1];
execvp("./slave", args);
} else {
waitpid(cpid, &status, 0);
sums[i] = WEXITSTATUS(status);
printf("Child returned the number %d\n", sums[i]);
sprintf(argv[i+1], "%d", sums[i]);
}
count += 2;
}
if(sums[0] == 0) {
printf("done\n");
} else {
main(argc/2, args);
}
}
first problem is that you did not allocate any memory for sums
and sums[i]
accesses a trashy location. do this:
int sums[argc];
Secondly, for execvp
function argument array has to have
1. [0] -- a legal string.
2. the last element [3] must be NULL
args[0] = "some-execution-file-name";
args[1] = argv[count];
args[2] = argv[count + 1];
args[3] = NULL;
Otherwise the function has no idea about the size of the array and slave can die trying to read element [0].