简体   繁体   中英

Processes in Linux: Getting every child process to sleep a Random number of seconds

I would like to make a variable (that belongs to a process) get a new random value, each time the new process starts.

I need this random generation to make every process created sleep a random number of seconds. At the beginning of the program I used srand(time(NULL)) , and in the function that the process would run I used

int sleeptime = rand() % 16 + 5; //that's because I need values from 5 to 20 int sleeptime = rand() % 16 + 5; //that's because I need values from 5 to 20 .

I've tried to implement such a thing, but I saw that for every process the value of the variable is the same.

I think that if I took as argument for srand(..) the current time in milliseconds (time at which the respective process begins) I would get the random values. The problem is I didn't find any information for this. The only thing suggested on different pages is the well known: srand(time(NULL)); (where time(NULL) returns the current time in seconds).

Can you, please, suggest me some way to implement this? Thank you in advance.

If you're on linux, you also seed the PRNG by reading from /dev/random . Something like this:

void seedprng() {
    unsigned i;
    FILE* f = open("/dev/random", "rb");
    if (f) {
        fread(&i, sizeof(i), 1, f);
        fclose(f);
        }
    else{
        printf("falling back to time seeding\n");
        i = (unsigned)time(NULL);
        }
    srand(&i)
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM