c - 使用 fork() 生成随机数

标签 c random process fork sleep

我的程序应该有 n 个子“进程”,这些子进程每秒生成一个 1 到 9 之间的随机数,我的问题是我应该验证子进程不会在同一时间生成相同的数字

例如,如果我有 5 个 child ,他们可以生成 5 4 8 2 1 但他们无法生成 “5 5”4 3 1

有人可以给我建议吗?

int main (int argc,char** argv)
{
    int i,pid,x,l;

    l=atoi(argv[1]);

    for(i=0;i<l;i++)
    {
        pid=fork();
        switch(pid)
        {
        case -1:
            printf("error\n");
        case 0: {
            srand(time(NULL));
            x=rand()%9+1;
            printf("Im child%d\n",x);sleep(1);
        }
        default:
            printf("Im parent %d\n",getpid());
        }
    }
}

最佳答案

您的子进程需要将它们选择的随机数传达给父进程。您可以做的是使用管道在父进程和每个子进程之间建立(2 路)通信。

我坚持2-way,因为如果 child 画错了,家长必须再次询问。

这是我不久前编写的一些样板代码,用于在父进程和子进程之间建立这种双向通信。发生的情况是,父级写入恰好是子级“stdin”的文件,而子级写入其 stdout,该文件也由父级读取。技术上它是用 C++ 编写的,但很容易适应 C。

我不明白在子进程中生成随机数的可能用例是什么。也许您应该使用线程而不是进程?

#include "process.h"
#include <assert.h>
#include <unistd.h>
#include <signal.h>
#include <cstring>
#include <iostream>

void Process::run(const char *cmd) throw (Err)
/*
 * Spawn a child process, and executes cmd. On success:
 * - pid is the process id
 * - in, out are FILE* to read/write from/to the process' stdout/stdin
 * */
{
    pid = 0;
    int readpipe[2], writepipe[2];
#define PARENT_READ     readpipe[0]
#define CHILD_WRITE     readpipe[1]
#define CHILD_READ      writepipe[0]
#define PARENT_WRITE    writepipe[1]

    try {
        if (pipe(readpipe) < 0 || pipe(writepipe) < 0)
            throw Err();

        pid = fork();

        if (pid == 0) {
            // in the child process
            close(PARENT_WRITE);
            close(PARENT_READ);

            if (dup2(CHILD_READ, STDIN_FILENO) == -1)
                throw Err();
            close(CHILD_READ);

            if (dup2(CHILD_WRITE, STDOUT_FILENO) == -1)
                throw Err();
            close(CHILD_WRITE);

            if (execlp(cmd, cmd, NULL) == -1)
                throw Err();
        } else if (pid > 0) {
            // in the parent process
            close(CHILD_READ);
            close(CHILD_WRITE);

            if ( !(in = fdopen(PARENT_READ, "r"))
                    || !(out = fdopen(PARENT_WRITE, "w")) )
                throw IOErr();
        } else
            // fork failed
            throw Err();
    } catch (Err &e) {
        cleanup();
        throw;
    }
}

void Process::cleanup()
{
    // close file descriptors
    if (in) fclose(in);
    if (out) fclose(out);

    // kill child process
    if (pid > 0) kill(pid, SIGKILL);
}

Process::~Process()
{
    cleanup();
}

void Process::write_line(const char *s) const throw(IOErr)
{
    fputs(s, out);
    fflush(out);    // don't forget to flush! (that's what she says)

    if (ferror(out))
        throw IOErr();
}

void Process::read_line(char *s, int n) const throw(IOErr)
{
    if (!fgets(s, n, in))
        throw IOErr();
}

关于c - 使用 fork() 生成随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21215606/

相关文章:

java - 从 C 转换为 Java

c - 在C数组中插入元素

MySQL - 连接同一个表 4 次,其中第 2,3 和 4 列随机且全部不同

python 3 : How to move an item from list x to list y and remove it from list x?

linux - 在远程存储库上使用 'git push -f' 是否会刷新整个文件夹?

c - 将 fork 进程输出重定向到 NULL

c - 在arduino中停止和启动循环

c - 我是否使用了错误的转换说明符或其他什么? scanf() 在 c 中不起作用

java - 计算使用java中的Random()方法生成的数字的平均值

c - 是否可以仅通过代码以管理员身份运行