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;
}