2013-04-09 7 views
2

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

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

Благодарим за помощь.

#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 
+0

Непонятно, что вы хотите сделать. Можете ли вы объяснить больше? – Bechir

+0

Родительский процесс должен собирать и печатать все входы дочерних процессов в конце сообщения. thank u :) –

ответ

2

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

во-первых, вы не пишете право 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; 
} 
+0

Я попытался запустить программу, но она не закончилась правильно, она застряла в последнем цикле! –

+0

Я имею в виду, что процессы не заканчиваются, как раньше. –

+0

@ AnisNouri Исправлено. Это было условие остановки для оператора 'for'. Он должен остановиться при этом условии 'i Bechir

Смежные вопросы