Search code examples
cfor-looprandomfork

rand() function, how can I get the nice


#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>

int main(){
        for(int i = 0; i <= 4; i = i + 1) {
                int p1;
                    p1 = fork();
                    wait(NULL);
                    int plato;
                   plato = rand()%2;
                   int cant;
                        cant = rand()%6 + 1;
                        int cant1;
                        cant1 = rand()%4 + 1;
                if (p1 == 0) {
                   if (plato = 0){
                        if (cant > 0){
                           printf("\nMesero %d, PPID=%d, pedido de %d postre/s", (i) ,getppid(), cant);
                        printf (", PID=%d\n", getpid());
                        }
                        exit(0);
              } else if (plato = 1){
                    printf("\nMesero %d, PPID=%d, pedido de %d plato/s de alboniga/s", (i) ,getppid(), cant1);
                        printf (", PID=%d\n", getpid());
                        exit(0);
              }
        } else if (p1<0) {
         printf("ERROR");
        }
}

         return 0;
}

The answer is always the same and I need diferent ones,

I want to generate a random type of "Platos" and if they are desserts or dishes generated a random amount


Solution

  • #include <time.h> and as the first statement in main() do srand(time(NULL));. This will create a new sequence of pseudo-random integers as long as you execute your program more than 1 second apart. On Linux /dev/random (blocking) and /dev/urandom (non-blocking) are alternative sources of entropy.