get a values from child to use it in parent
i wrote the code below but the last printf return 0 for sumofall how can i get the values of sumoro,sumort and sumorth from child
the code :
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
int main()
{
in开发者_高级运维t array[3][3];
int sumoro = 0,sumort = 0,sumorth = 0;
pid_t pid = fork();
if (pid < 0) {
printf("fork faild");
exit(1);
}
else {
if (pid == 0)
{
for (int i = 0; i < 3 ; i++) {
for (int j = 0; j < 3; j++) {
array[i][j] = rand()%9;
if (i == 0)
sumoro += array[0][j];
if (i == 1)
sumort += array[1][j];
if (i == 2)
sumorth += array[2][j];
}
}
}
else {
waitpid(pid, NULL, 0);
int sumofall = sumoro + sumort + sumorth;
printf("sum of all equal : %d ", sumofall);
}
return 0;
}
}
Note : not necessarily but if you can help me, how can i make the rand() gives everytime new numbers because i notice every time same values
When you fork, each process resides in its own space afterwards. There is no easy way to move data back and forth - at least nothing as simple as reading a variable. You need to use some kind of Inter-Process Communication (IPC) method, such as anonymous pipes (see the pipe(2) manual page).
As for rand(), you need to seed the random number generator with a relatively random value. A simple solution with adequate randomness for pretty much anything but cryptography is issuing this statement once at the beginning of your program:
srand(time(NULL));
This uses the clock to seed the RNG with different values each time that you run your program, unless you manage to run it twice withing the same second.
Basically the part where you add up your values and where you print them are on different processes.
For rand() what you need to do is initialize it with a seed, by default it is seeded with 0, that's why it's always giving you the same sequence (how are you seeing the values rand gives you anyway?). What is usually done is to seed it with the time/date so that it's always different, try using
srand ( time(NULL) );
for that make sure to #include <time.h>
精彩评论