Hello All, I am stuck up in a program where the rand functions ends up giving all the same integers. Tried sleep, but the numbers turned out to be same... Can anyone help me out how to fix this issue ? I have called the srand once in the program, but I feel like when I call fork the child process again calls the srand.. any fix for that ?
This is my working code (just the rand function messing up)
int main (int argc, char *argv[])
{
int seed = time(0);
sleep(10);
srand(seed);
int i, nproc;
nproc = atoi(argv[1]);
pid_t child[nproc];
int status;
if (argc < 2)
{
fork(); // if no argument - only one child process is created
}
else
{
for(i = 0; i < nproc; i++)
{
switch(pid = child = fork())
{
case -1:
perror("fork-error");
exit(1);
case 0:
printf("id = %d : RND = %d",i, (int)(rand()% 100 +1)); //generating random number for each child
exit(i);
default:
waitpid(child, &status, 0); //wait for the child to terminate
printf("Exiting %d = %d\n", i, WEXITSTATUS(status));
break;
}
}
}
return 0;
}