This is for a school assignment, and I know this is about a simple problem as there is, but for the life of me I can't figure out what I am doing wrong.
In the parent process, I need to convert cmdline arguments to integers, then store the arguments in a malloc array. I then need to send each integer to the child process one at a time. The child process will then sum all of the integers passed from the parent process. Once the summation is complete, it will return the sum to the parent process. The parent process then prints out the sum.
There are 3 things I do not understand about this code.
- Taking command line arguments, converting them into integers, and storing them using a pointer to a
mallocarray. I do not understand why I can't just write this in my parent process:
int* numArray = (int*) malloc (argc * sizeof(int));
for(int i = 0; i < argc; ++i){
numArray[i] = atoi(argv[i+1]);
}
How can I send individual values to child process for summation? I can read them one at a time, and then increment sum by the value in
sumBuf. ThensumBufgets overwritten with the next value, and increments sum bysumBufagain. How can I do this?How can I access the child's return value in the parent process?
Storing the integers in the malloc array yields a segmentation fault, and I do not understand how to correct this. also, since fork returns the child's PID, if the child returns a sum, shouldn't the sum be the child's PID?
- For the
mallocarray I have tried de-referencingnumArrayinside the for loop like:
*numArray[i] = atoi(argv[i+1])
I have tried writing individual values to the pipe within a for loop
I know that fork returns the child PID value, so if child returns sum, shouldn't sum = p, store sum into the parent's sum value?
int main(int argc, char **argv){ int *numArray = (int*) malloc (argc * sizeof(int)); pid_t p; int fd[2]; pipe(fd); p = fork() //error checks if(p == 0){//child process int sum = 0; int sumBuf = 0; close(fd[1]);//close write end for(int i = 0; i < argc; ++i){ read(fd[0], sumBuf, sizeof(int)); sum += sumBuf; } close(fd[0]);//close read end return sum;//return sum from child process } else{//parent process int sum = 0; close(fd[0]);//close read end for(int i = 0; i < argc; ++i){ numArray[i] = atoi(argv[i+1]); write(fd[1], numArray[i], sizeof(int)); } close(fd[1]);//close write end of pipe sum = p; printf("Sum = %d", sum); return 0; } free(numArray); return 0; }
I get a segmentation fault message when I try to run this program. Please don't call me stupid, I understand the idea of what to do, but I don't understand how to implement it..
i == argc -1, what isargv[i+1]?atoi(argv[argc])?