mardi 16 mars 2021

generating a random wait time for each child after fork

I have this source code here that has a required random number generating function build in called randG(); the problem is when i fork off 5 children and call the function 5 times in each child, i get the same number 5 times. is there a fix for this? I need each number to be individual and specific. Thanks!

source code:
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <stdlib.h>
#include <math.h>


int randG(int mean, int stddev) {
  double mu = 0.5 + (double) mean;
  double sigma = fabs((double) stddev);
  double f1 = sqrt(-2.0 * log((double) rand() / (double) RAND_MAX));
  double f2 = 2.0 * 3.14159265359 * (double) rand() / (double) RAND_MAX;
  if (rand() & (1 << 5))
    return (int) floor(mu + sigma * cos(f2) * f1);
  else
    return (int) floor(mu + sigma * sin(f2) * f1);
}

int perform() {

  int mean[2] = {
    9,
    11
  };
  int stdDev[2] = {
    3,
    7
  };

  int semID;
  int procID;
  int eatI;
  int thinkI;
  int eatTime[6] = {0, 0, 0, 0, 0, 0};
  int thinkTime[6] = {0, 0, 0, 0, 0, 0};

  //printf("%d \n", (0 % 4));
  struct sembuf using[5] = { {0, -1, 0}, {1, -1, 0}, {2, -1, 0}, {3, -1, 0}, {4, -1, 0} };
  struct sembuf use[5] = { {0, 1, 0}, {1, 1, 0}, {2, 1, 0}, {3, 1, 0}, {4, 1, 0} };

  semID = semget(IPC_PRIVATE, 5, IPC_CREAT | 0600);

  for (int dan = 0; dan < 5; dan++) {
    semop(semID, & use[dan], 1);
    printf("%d \n", (randG(11, 7)));
  }

  for (int x = 0; x < 5; x++) {
    procID = fork();
    int philNo = x + 1;

    if (procID == 0) {

    } else {

      // thinking
      sleep(rand() % 2);
      thinkI = randG(11, 7);
      thinkTime[x] = thinkTime[x] + thinkI;
      printf("philosopher No: %d is thinking for: %d sec total of: %d \n", philNo,
        thinkI, thinkTime[x]);
      sleep(thinkI); // think for the amount of seconds randomly
      // generated by the randG (random gaussian) formula.
      // thinking end.

      // eating
      semop(semID, & using[2], 1);
      printf("snatching the second resource %d \n", philNo);
      semop(semID, & use[2], 1);
      sleep(0.01);
      // eating
      exit(0);
    }

  }

}

int main(int argc, char
  const * argv[]) {

  perform();
  return 0;
}

produces the undesired output of:

philosopher No: 1 is thinking for: 4 sec total of: 4
philosopher No: 2 is thinking for: 4 sec total of: 4
philosopher No: 3 is thinking for: 4 sec total of: 4
philosopher No: 4 is thinking for: 4 sec total of: 4
philosopher No: 5 is thinking for: 4 sec total of: 4



Aucun commentaire:

Enregistrer un commentaire