The random number between forked processes is the same

I am starting several processes from the manager process. Then I would like to randomize the port number for these forked processes to listen on. However, when I seed randomly 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 tried seeding in the manager and then tried rand in the process, but I still have the same problem getting the same number when I can rand. Can I sow anything other than time and still get good random results.

+1


source to share


2 answers


Since the time will be the same for each process, you need a different input that is guaranteed to be different between processes. The process number is appropriate for this. Combine them by adding the process number at time.



+1


source


Seed with (pid % RAND_MAX) ^ WHATEVER

- This guarantees a different seed for each process.



You can define WHATEVER

for a specific value or (time(NULL) % RAND_MAX)

if you want even less predictability.

+1


source







All Articles