c - rand 命令行并发编程

标签 c random concurrency

您好,我在使用并发编程生成随机数时遇到了一些问题,在 exit() 上,我想使用 rand -M 6 但我没有知道如何,我尝试以某些方式使用 rand() 但 child 总是返回相同的数字。非常感谢。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/sysinfo.h>
#include <sys/wait.h>
#include <errno.h>
#include <time.h>
#include <string.h>
#define NUM_KIDS 5

int i, sum;

int main()
{
    pid_t child_pid;
    int status;

    for (i=0; i<NUM_KIDS; i++) {
        switch (child_pid = fork()) {
        case -1:
            /* Handle error */
                fprintf(stderr,"Error #%03d: %s\n", errno, strerror(errno));
                break;

        case 0:
            /* Perform actions specific to child */

        printf("Hi, my PID is %d\n", getpid());

        exit(/*here i'd like to use rand -M 6*/);
        printf("Hi, my PID is %d and you should never see this message\n", getpid());
        break;

        default:
            /* Perform actions specific to parent */
            printf("I'm the proud parent with PID %d of a child with PID %d\n", getpid(), child_pid);
            break;
        }
    }

    i = 0;

    while ((child_pid = wait(&status)) != -1) {
        printf("PARENT: PID=%d. Got info of child with PID=%d, status=%d\n",
               getpid(), child_pid, status/256);
        sum += status/256;
    }
    if (errno == ECHILD) {
        printf("In PID=%6d, no more child processes, sum: %d\n", getpid(), sum);
        exit(EXIT_SUCCESS);
    }
    return 0;
}

最佳答案

您需要使用 srand(unsigned int) 作为随机数生成器的种子。

种子只是启动随机数公式的数字。使用相同的种子,将始终显示相同的数字序列。我建议使用 time.h 中的 clock() 或自 1970 年 1 月 1 日以来的秒数(计算机中的时间通常存储为自 1970 年 1 月 1 日以来的秒数)为 rand() 播种。

关于c - rand 命令行并发编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47189759/

相关文章:

python - 获取 numpy.random 分布列表

c - 同时生成真正的随机整数?

MySQL,加载数据并发本地,禁用和启用键

api - 列出所有 Asana 工作区任务

java - Java 中的同步行为不正确?

C SECCOMP 阻塞或关闭 STDIN/STDOUT

c - 请解释这段代码在做什么(someChar - 48)

java - randomUUID 是否提供唯一 ID?

c - 如何创建一个创建 sdl 窗口和渲染器的函数(当 sdl 窗口和渲染器作为参数传递时)?

c - 在c中动态增加数组(int *)的大小