我写了下面的代码,但是最后一个 printf 为 sumofall 返回 0 我怎样才能从 child 那里得到 sumoro、sumort 和 sumorth 的值
代码:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
int main()
{
int 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;
}
}
注意:不一定,但如果你能帮助我,我怎样才能使 rand() 每次都给出新数字,因为我每次都注意到相同的值
最佳答案
当你 fork 时,每个进程之后都驻留在自己的空间中。没有简单的方法来回移动数据——至少没有像读取变量那样简单的方法。您需要使用某种进程间通信 (IPC) 方法,例如匿名管道(请参阅 pipe(2) 手册页)。
至于 rand(),您需要为随机数生成器提供一个相对随机的值。一个简单的解决方案,它具有足够的随机性,适用于除密码学之外的几乎所有内容,它是在程序开始时 一次 发出此语句:
srand(时间(NULL));
这会在您每次运行程序时使用时钟为 RNG 播种不同的值,除非您设法在同一秒内运行两次。
关于c - 从 child 那里获取值以在 parent 中使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4269596/