Random number between forked processes is the same

2019-07-15 10:40发布

问题:

I am forking multiple processes from a manager process. I then would like to make a random port number for these forked processes to listen on. However, when I seed random, and get a random number, I get the same number between the three processes. For example:

manager:

int main(){
 for(int i = 0; i < rCount; i++){
  pid_t pid = fork();
  if (pid == 0) {// child
        execl(ROUTERLOCATION,"",NULL); //create router process
   }
   else { // parent
    }
  }
}

router:

int main(){
  randomPort(); 
}
void randomPort(){
    srand(time(NULL));
    int host_port = rand() % 99999 + 11111;
    cout << houst_port << endl;
}

I have tried seeding at the manager, and then trying rand at the process, but I still have the same problem of getting the same number when I can rand. Can I seed with anything besides the time, and still get good random results.

回答1:

Since the time will be the same for every process, you need another input that is guaranteed to be different between the processes. The process number works well for this. Combine the two by adding the process number to the time.



回答2:

Seed with (pid % RAND_MAX) ^ WHATEVER -- this will guarantee a different seed for each process.

You can define WHATEVER to a specific value, or (time(NULL) % RAND_MAX) if you want even less predictability.