![]() |
c-unix-childprocesses-random number
well, the parent process is supposed to fork out two child processes and each of the child process are supposed to come up with a random integer between 0 and 1 and do a lot of other things
however, each child process is supposed to do identical things, therefore, i wrote the same function (say functionc()) for both of them and just passed appropriate parameters to them. I am using rand () to come up with the random number in functionc() [HTML]int choice = rand() % 2;[/HTML] now the problem is both child process always come up with the same random number. In other words, either both child processes will come up with 1 or both child processes will come up with 0 ... I am guessing part of the problem is they are using exactly identical memory images, so even the random number generator is generating the same number for both of them? is there any way i fix that apart from writing different functions for both of them, which doesnt so sound sophiscated when both of them are supposed to do exactly same thing except come up with different random number occassionalyy |
oh btw I tried
[HTML]srand(getpid()); int choice = rand() % 2; // random integer - 0 and 1 [/HTML] the problem will this is it will ALWAYS alternate LOL lol i want something that will alternate sometimes, sometimes it wont ... something like that |
There's no such thing as an integer between 0 and 1. Google 'integer'.
|
srand(time(NULL) % getpid() );
And DaWei is correct. You want int choice= rand()%2; choice ++; This gives 1 or 2. If you really want .0 ... .999999 then double choice=rand(); double next=rand(); choice=(next > choice) ? choice/next : next/choice; or use something like drand48(); |
Quote:
i meant either 0 and 1, not "between 0 and 1" sorry :confused: |
well you could perform some calculations with PID, such as add to how it many milliseconds have passed.
|
Quote:
because I called srand function inside the while loop i called it outside the while loop and now it gives pretty random results thanks folks |
Yup. Seed it just once. If you seed it with the same value more than once, you'll get a repeat of the "random" numbers.
|
| All times are GMT -5. The time now is 1:56 AM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC