jeudi 24 septembre 2020

using Pipes create N child and send message to parent

I'm trying to create n child with the same parent, and send the random number from child -> parent. For now, I have a problem to send random 0/1 from child -> parent.

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

int main() 
{ 
pid_t pids[10];
int i;
int n = 10;

/* Start children. */
for (i = 0; i < n; ++i) {
     if ((pids[i] = fork()) < 0) {
     perror("fork");
         abort();
  } else if (pids[i] == 0) {
   // printf("I am a child with id %d and my parent %d\n",getpid(),getppid());
    int random = rand() % 2;
    printf("\nChild send random: %d\n",random);
    write(pids[1], &random, sizeof(random));    
    exit(0);
    }
   else{
    int ran;
    read(pids[0], &ran, sizeof(ran)); // read from child
    printf("\nParent Received: %d\n", ran);
    }
  
}

wait(NULL);

 }
 



Aucun commentaire:

Enregistrer un commentaire