jeudi 19 janvier 2017

Generate random numbers on forked processes in c

Im trying to create a multiprocess program in c. the main process will start 3 processes, each will do its job ( sleep for 1-10 sec ) and will report that he is done. The problem im facing is about generating the random numbers. i got the same numbers always ( randomized between each running, but constant between all forked processes. Is it a buggy code ? (im new to 'c') Is it the behavior of a forked process ? if it is, how can i generate random numbers ?

#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>

int main(int argc, char **argv){
    // srand(time(NULL));
    printf("starting main proc [%d]\n", getpid());
    // start 3 processes
    for (int i=0; i<3; i++){
        exec_waiting_proc(i);
    }
    return 0;
}
// sleeper process
int exec_waiting_proc(int id){
    int pid;
    pid = fork();
    if (pid == 0){
    // child
        srand(time(NULL));
        int parent_id =  getppid();
        int sleep_seconds = (rand() % 10) + 1;
        printf("%d\n", sleep_seconds);
        //sleep(r);
        printf("child-%d [%d], done... my parent: [%d]\n", id, getpid(), parent_id);
        _exit(0);
    } else {
    // parent
        printf("parent [%d]: starting process %d\n", getpid(), pid);
    }
    return 0;
}

output example : (2 times)

chen ~/dev/c/geany/ ./ptr2 
starting main proc [25801]
parent [25801]: starting process 25802
parent [25801]: starting process 25803
8
child-0 [25802], done... my parent: [25801]
parent [25801]: starting process 25804
8
child-1 [25803], done... my parent: [25801]
8
child-2 [25804], done... my parent: [3077]
chen ~/dev/c/geany/ 
chen ~/dev/c/geany/ 
chen ~/dev/c/geany/ ./ptr2 
starting main proc [25805]
parent [25805]: starting process 25806
parent [25805]: starting process 25807
parent [25805]: starting process 25808
7
child-0 [25806], done... my parent: [25805]
7
child-1 [25807], done... my parent: [25805]
7
child-2 [25808], done... my parent: [3077]
chen ~/dev/c/geany/ 




Aucun commentaire:

Enregistrer un commentaire