Связь между процессами с трубами

Я пытаюсь реализовать программу, которая принимает последовательность параметров на входе и в зависимости от этого создает равное количество процессов, реализованных с помощью каналов, где каждый процесс записывает в канал, а затем передает его отцу.

вот мой код, он не делает то, что мне нужно.

Спасибо за помощь .

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



int main(int argc ,char *argv[])
{
 int i,pid;
 int fd[2];//crea i descriptor 
 char phrase[30][30];//crea il buffer
 pipe(fd); /* crea la pipe */

     // Genera i 10 processi
  for(i=0;i<argc-1;i++)
  {
   if((pid=fork())==0)
    {               
      strcpy(phrase[i], argv[i+1]);  
      printf("ho scritoo :'%s'\n",*phrase);
      close(fd[0]);                         /* chiude in lettura */
      write(fd[1],phrase,strlen(*phrase)+1); /* invia anche 0x00 */
      close (fd[1]);                   // chiude in scrittura
                                // pid=0 -> figlio
      usleep(50000*(1+i));      // Ritardo iniziale
      printf("Figlio: %d\n",i+1);   // Stampa messaggio del figlio
      usleep(500000*(1+i));     // Ritardo finale
      return(101+i);            // Termina con codice di ritorno
       } 
   else { 
        printf("Ho generato il figlio %d con pid %d\n",i+1,pid);
        char message[100];    //creare il buffer 
        memset(message,0,100);
        int bytesread;  
        close(fd[1]);                         /* chiude in scrittura */
        bytesread = read(fd[0],message,sizeof(message));
        printf("ho letto dalla pipe %d bytes: '%s' \n",bytesread,message);
        close(fd[0]);
    }
  }

  // Attende che dieci processi terminino
  for(i=0;i<argc-1;i++)
  {
    int status;
    wait(&status);      // Attende termine di un figlio (uno qualunque)
    printf("Terminato processo %d\n",WEXITSTATUS(status));
  }
}

Ввод: ./pipes cmd1 cmd2 cmd3

 I created the first child with pid 21552
 I wrote: 'cmd1'
 I read from the pipe 5 bytes: 'cmd1'
 I created the second child with pid 21553
 I read from the pipe -1 bytes:''
 I wrote: ') ML?'
 I created the third child with pid 21554
 I read from the pipe -1 bytes:''
 I write: ') ML?'
 Son: 1
 Son: 2
 Son: 3
 Ended process 101
 Ended process 102
 Ended process 103

person Anis Nouri    schedule 09.04.2013    source источник
comment
Непонятно, чем вы хотите заниматься. Вы можете объяснить больше?   -  person Bechir    schedule 09.04.2013
comment
Родительский процесс должен собрать и распечатать все входные данные дочерних процессов в конце коммуникации. Спасибо :)   -  person Anis Nouri    schedule 09.04.2013


Ответы (1)


У вас есть две проблемы:

Во-первых, вы не пишете правильный phrase в трубу. Вы все время пишете phrase. Для первого ребенка это нормально, для остальных это будет пустая строка.

Во-вторых, вы закрываете fd[0] после создания первого дочернего элемента. Вы никогда не получите данные от другого процесса.

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

int main(int argc ,char *argv[])
{
    int i,pid;
    int fd[2];//crea i descriptor 
    char phrase[30][30];//crea il buffer
    pipe(fd); /* crea la pipe */

    for(i = 0; i < argc - 1 ; i++)
    {
        if((pid=fork())==0)
        {               
            strcpy(phrase[i], argv[i+1]);  
            printf("ho scritoo :'%s'\n",phrase);
            close(fd[0]);                         /* chiude in lettura */
            write(fd[1],phrase[i],strlen(phrase[i])+1); /* invia anche 0x00 */
            close (fd[1]);                   // chiude in scrittura
            // pid=0 -> figlio
            usleep(50000*(1+i));      // Ritardo iniziale
            printf("Figlio: %d\n",i+1);   // Stampa messaggio del figlio
            usleep(500000*(1+i));     // Ritardo finale
            return(101+i);            // Termina con codice di ritorno
        } else { 
            printf("Ho generato il figlio %d con pid %d\n",i+1,pid);
            char message[100];    //creare il buffer 
            memset(message,0,100);
            int bytesread;  

            bytesread = read(fd[0],message,sizeof(message));
            printf("ho letto dalla pipe %d bytes: '%s' \n",bytesread,message);
            // close(fd[0]);
        }
    }
    close(fd[0]);                         /* chiude in scrittura */
    close(fd[1]);                         /* chiude in scrittura */
    // Attende che dieci processi terminino
    for(i=0;i<argc-1;i++)
    {
        int status;
        wait(&status);      // Attende termine di un figlio (uno qualunque)
        printf("Terminato processo %d\n",WEXITSTATUS(status));
    }
    return 0;
}
person Bechir    schedule 09.04.2013
comment
Я попытался запустить программу, но она не завершилась должным образом, она застряла в последнем цикле for! - person Anis Nouri; 09.04.2013
comment
Я имею в виду, что процессы не заканчиваются так, как раньше. - person Anis Nouri; 09.04.2013
comment
@AnisNouri Исправлено. Это было условие остановки оператора for. Он должен остановиться в этом состоянии i < argc - 1 - person Bechir; 09.04.2013