vendredi 25 mars 2016

C, rand function doesn't work properly with sleep() function

First of all, I know there is a lot of questions about rand() function but I think this is different.

Actually rand() function always works properly when I didn't combine with sleep() function. I tried it. But when I combine rand() function with sleep() like this "sleep(rand() %5)", sometimes it works well for all child processes, sometimes works well for first 4-5 times, after that it becomes 0 for other children. And sometimes it is always 0 for all child processes.

About my code:

I want to fork 8 children from parent process and print their pid numbers one by one. But I should use sleep function after creating a child. Sleep time should be random. I used time() function as a seed and try to use rand function but it doesn't work properly with sleep function.

Here is my code:

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


void childs();
void parent();


int id;
int i;
int pidID[9];
int fd[2];
char buff[100];
int main(int argc, char *argv[]){
    pid_t child;
    for(i = 0; i < 8; i++){
        pipe(fd);

        child = fork();
        wait(NULL);
        if(child){
            parent();
            continue;
        }else if(child == 0){
            childs();
            break;
        }else{
            perror("State\n");
            exit(1);
        }
    }
    if(child ==0){
    printf("I am a child pid: %d, ppid: %d pidno: %d\n", getpid(), getppid(),pidID[i+1]);
    }else{
    printf("I am a parent pid: %d, ppid: %d pidno: %d\n", getpid(), getppid(),pidID[0]);
    }

}


void childs(){
id = getpid();
pidID[i + 1] = id;
char swap[50];
sprintf(swap, "%d" ,id);
write(fd[1], swap, 10);
srand(time(NULL));
int randomTime = rand() %5;
printf("Random time: %d\n",randomTime);
sleep(randomTime);
}



void parent(){
pidID[0] = getpid();
read(fd[0], buff , 10);
printf("Buff: %s\n", buff);
}




Aucun commentaire:

Enregistrer un commentaire