I’m taking a class on how to learn programming multi process programs on linux on university. I’m still very green and trying my best to learn, so any thing you might see that is wrong would be welcome.
I have a problem that asks me to iterate an array, one half on main process, the other half on the child process. I wrote code that does that, but the problem is, i’ve noticed if i run a few times the binary, the main(father) process from times to times segmentations faults.
Please have a look at the code, and tell me what’s wrong with it or if i am missing a key aspect of this type of programming. My answer starts after the comment //answer starts here.
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <sys/wait.h> #include <sys/types.h> #include <unistd.h> #define ARRAY_SIZE 1000 int main() { int numbers[ARRAY_SIZE]; /* array to lookup */ int n; /* the number to find */ time_t t; /* needed to initialize random number generator (RNG) */ int i; /* intializes RNG (srand():stdlib.h; time(): time.h) */ srand((unsigned)time(&t)); /* initialize array with random numbers (rand(): stdlib.h) */ for (i = 0; i < ARRAY_SIZE; i++) numbers[i] = rand() % 10000; /* initialize n */ n = rand() % 10000; //answer starts here int half = n / 2; int count = 0; int pid_status = 0; pid_t pid_f = fork(); if (pid_f == -1) { return EXIT_FAILURE; } else { if (pid_f == 0) // child process iterates half end of the array { for (i = half; i < ARRAY_SIZE; ++i) { if (numbers[i] == n) { count++; } } printf("Sons counter:%dn", count); exit(count); } //else it's the father process else { for (i = 0; i < half; ++i) { if (numbers[i] == n) { count++; } } waitpid(pid_f, &pid_status, 0); printf("Father counter:%dn", count); if (WIFEXITED(pid_status)) { count += WEXITSTATUS(pid_status); } printf("Sum is=%dn", count); } } return 0; }
Advertisement
Answer
The segmentation fault is caused by n being out of bounds sometimes:
n = rand() % 10000; //answer starts here int half = n / 2;
Half can be 5000, but numbers is only 1000 elements.
Maybe you meant:
n = rand() % 1000;