How to generate two child processes in which each one writes a string in the PIPE and the parent process le PIPE and joins the two strings?

0

include

include

include

include

include

include

int main (void) {         int status = 0;         int fd [2], nbytes;         pid_t pid, wpid;         char string1 []="Hello, \ n";         char string2 []="World! \ n";         char readbuffer [256];         char cid;         pipe (fd);

    for (cid = 0; cid < 2; cid++)
    {
      printf("Filho criado! id = %d \n", cid);

      if((pid = fork()) == -1)
      {
              perror("fork");
              exit(1);
      }

      else
      {

        if(pid == 0 && cid == 0)
        {
          /* Child process closes up input side of pipe */
          close(fd[0]);

          /* Send "string" through the output side of pipe */
          write(fd[1], string1, (strlen(string1)+1));
          exit(0);
        }

        else if(pid == 0 && cid == 1)
        {
          /* Child process closes up input side of pipe */
          close(fd[0]);

          /* Send "string" through the output side of pipe */
          write(fd[1], string2, (strlen(string2)+1));
          exit(0);
        }

        else if (pid > 1)
        {
          printf("Eu sou o Papai !\n");
        }
      }
    }

    /*wait for childs*/
    while((wpid = wait(&status)) > 0);

    /* Parent process closes up output side of pipe */
    close(fd[1]);

    /* Read in a string from the pipe */
    nbytes = read(fd[0], readbuffer, sizeof(readbuffer));

    printf("Received string: %s", readbuffer);

    return(0);

}

    
asked by anonymous 22.04.2018 / 04:58

0 answers