I want to assign a random variable to every child. For example Child 1 gets a value of 0.515 and Child 2 gets a value of 0.911.
I tried the following code:
#define _POSIX_C_SOURCE 199309L
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
double random()
{
double x = rand() / (double)RAND_MAX;
return x;
}
int main()
{
int N = 10;
pid_t pids[N];
for (int i = 0; i < N; ++i)
{
if ((pids[i] = fork()) < 0)
{
printf("Error using fork().\nExiting...\n");
exit(-1);
}
else if (pids[i] == 0)
{
// get random value
double result = random();
printf("Child %d PID = %d. random() = %f.\n", i, getpid(), result);
exit(0);
}
}
while (N > 0)
{
wait(NULL);
N--;
}
printf("Done.\n");
return EXIT_SUCCESS;
}
Which generates the following output:
Child 0 PID = 6531. random() = 0.840188.
Child 1 PID = 6532. random() = 0.840188.
Child 2 PID = 6533. random() = 0.840188.
Child 3 PID = 6534. random() = 0.840188.
Child 4 PID = 6535. random() = 0.840188.
Child 5 PID = 6536. random() = 0.840188.
Child 6 PID = 6537. random() = 0.840188.
Child 7 PID = 6538. random() = 0.840188.
Child 8 PID = 6539. random() = 0.840188.
Child 9 PID = 6540. random() = 0.840188.
Done.
As we can see every child gets the same random value, but I want them to all have different values.
Why do they all get the same number and how can I prevent this?
All child processes are starting with the same random seed and each calls rand
once. This is why they all have the same value.
You should call rand
in the parent process before forking, that way you get different random numbers. Then after the fork the child will have the value that was generated before the fork.
for (int i = 0; i < N; ++i)
{
// get random value
double result = random();
if ((pids[i] = fork()) < 0)
{
printf("Error using fork().\nExiting...\n");
exit(-1);
}
else if (pids[i] == 0)
{
printf("Child %d PID = %d. random() = %f.\n", i, getpid(), result);
exit(0);
}
}