首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >rand命令行并发编程

rand命令行并发编程
EN

Stack Overflow用户
提问于 2017-11-09 05:10:36
回答 2查看 46关注 0票数 0

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

代码语言:javascript
复制
#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;
}
EN

回答 2

Stack Overflow用户

发布于 2017-11-09 05:18:01

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

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

票数 1
EN

Stack Overflow用户

发布于 2017-11-09 05:29:44

从子进程调用rand()的问题在于,它始终是该进程中对rand() 的第一个调用,因此每次调用的值都是相同的。

相反,您可以在父对象的数组中生成返回值,然后子对象可以从数组中获取他们想要的值。

代码语言:javascript
复制
int main()
{
    pid_t child_pid;
    int status;
    int rvals[NUM_KIDS];

    srand(time(NULL));
    for (i=0; i<NUM_KIDS; i++) {
        rvals[i] = rand();
    }

    for (i=0; i<NUM_KIDS; i++) {
        ...
        case 0:
           printf("Hi, my PID is %d\n", getpid());
           exit(rvals[i]);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47189759

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档