Why does each child process generate the same "random" number when using rand() in c? -
i trying spawn n child processes, let each child process request random number of resources. however, each child requests identical number of resources, though number changes each time run program.
/* create appropriate number of processes */ int pid; for(int = 0; < numberofprocesses; i++){ pid = fork(); if(pid < 0){ fprintf(stderr, "fork failed"); exit(1); } else if(pid == 0){ time_t t; srand((unsigned) time(&t)); printf("child (%d): %d.", i+1, getpid()); /* generate random number [0, max_resources] of resources request */ int requestnum = rand() % (max_resources + 1); printf(" requesting %d resources\n", requestnum); exit(0); } else{ wait(null); } }
update: following seems have solved issue. thank help, commented!
time_t t; srand((int)time(&t) % getpid());
you seeding random number generator current time. it's same time children. forking child processes, checking clock in parallel. whole point of parallelism multiple things @ same time.
from man time()
:
time() returns time number of seconds since epoch, 1970-01-01 00:00:00 +0000 (utc).
notice in seconds. second long time running process. if tried sequentially (not parallel) on , over, highly 2 processes ask time, , same result.
design better way seed random number generator based on unique each process. could, example, add process id of child seed (getpid()
, not pid
).
Comments
Post a Comment