입력 시퀀스에서 매개 변수 시퀀스를 사용하는 프로그램을 구현하려고합니다. 파이프에 의해 구현되는 동일한 수의 프로세스를 생성한다는 점에 따라 각 프로세스는 파이프에서 작성한 다음 전달합니다 아버지에게.파이프와 프로세스 사이의 통신
여기 내 코드이며, 내가 필요한 것을하지 않습니다.
도움에 감사드립니다.
#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
당신이하고 싶은 것이 명확하지 않습니다. 더 설명해 주시겠습니까? – Bechir
부모 프로세스는 통신이 끝나면 모든 하위 프로세스 입력을 수집하여 인쇄해야합니다. u 고마워요. –