Home > database >  C: multiple child process each generate different random number
C: multiple child process each generate different random number

Time:03-30

I am trying to let children to process different random value EVERYTIME. If there is 3 children, I want them to generate 3 different random value each, so in total 3*3=9 different number. I've tried many srand(), if I go srand(time(NULL)) , all the children produces three same random number(123, 123, 123), and if I put getpid() into srand(), each child produces a random number three times(111,222,333). But I can't find something that produces 9 different random values. Here are my codes.

int main(int argc, char const *argv[]){
  int pid[6];
    for (int i = 0; i < 3; i  ) {
        pid[i] = fork();
        if (pid < 0) {
            printf("Fork Failed\n");
            exit(0);
        }
        if (pid[i] == 0) {
            time_t t;
            srand((int)time(&t) % getpid());
            int r = rand() % 30;
            int count = 0;
            while (count < 3){
                printf("Child %d: %d\n",i 1,r);
                count  ;
            }
            exit(0);
        }
  }
  return 0;
}

CodePudding user response:

You only call rand() once in each child (outside the while (count < 3) loop, and then you print out that same number three times in a loop. Note that you do not assign any new value to r between loop iterations, so naturally its value hasn't changed when you print it again.

If you want three different numbers, call rand() three times (inside the loop). Replace

        int r = rand() % 30;
        int count = 0;
        while (count < 3){
            printf("Child %d: %d\n",i 1,r);
            count  ;
        }

with

        int count = 0;
        while (count < 3){
            int r = rand() % 30;
            printf("Child %d: %d\n",i 1,r);
            count  ;
        }
  • Related