0

Hi i've got some problems with generating random numbers with concurrency programming, on exit() i would like ti use rand -M 6 but i don't know how, i've tried to use rand() in some ways but the childrens always returns the same number. Thanks a lot.

#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;
}
Zeno Raiser
  • 207
  • 2
  • 10

2 Answers2

1

You need to seed the random-number generator with srand(unsigned int).

The seed is just a number that initiates the random-number formula. With the same seed, the same sequence of numbers will always show up. I recommend seeding rand() with either clock() from time.h, or the time since January 1, 1970 in seconds (time in computers is often stored as the number of seconds since January 1, 1970).

Cpp plus 1
  • 990
  • 8
  • 25
1

The problem with calling rand() from the child process is that it will always be the first call to rand() in that process, so the value will always be the same each time.

What you can do instead is generate the return values in an array in the parent, then the children can grab the value they want from the array.

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]);
dbush
  • 205,898
  • 23
  • 218
  • 273