c - 从 child 那里获取值以在 parent 中使用它

标签 c linux fork

我写了下面的代码,但是最后一个 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/

相关文章:

perl - 从 Perl 获取子进程

c - 我应该在 scanf() 中同时包含 fflush(stdin) 和空格,还是只包含其中之一就足够了?

c - 如何将文本从文件复制到字符串数组?

c - Cormen 在 C 中实现的 Heapsort 算法,无法正常工作

linux - 如何包含相关脚本源文件bashrc

c++ - 如何编译独立的 OpenCV 可执行文件?

c - 不使用pthread_detach或pthread_join,不会为其他新创建的线程清理资源吗?

c++ - 需要帮助理解 fork C++

c++ - Linux fork 和 Kill 后停止创建核心转储文件

ios - 在 Xcode iOS 中链接 C 库