Also versuche ich ein Programm zu erstellen, das Benutzereingaben akzeptiert (Preis für Beispiel 50) und dann das erste Kind es an zweite, zweite eine 10 (Preis ist jetzt 60), dritte eins weitergibt dann 50 (Preis ist jetzt 110) und 4 man druckt nur/gibt den Endpreis zurück. Ich habe Fork in Loop und ich erstelle Rohre, aber der Preis ist immer der gleiche, nur 10 wird in jedem Kind hinzugefügt. Was ist falsch oder wie repariere ich das, damit es so funktioniert wie ich es möchte?C unbenannte Rohre und Gabel zur Berechnung
Mein Code:
int main(int argc,char *argv[])
{
int anon_pipe[2];
int n,N=4;
char value_price[100];
if(argc>1)
{
int price=atoi(argv[1]);
printf("%d\n",price);
if(pipe(anon_pipe)==-1){
perror("Error opening pipe");
return -1;
}
for(n = 0; n < N; n++){
switch(fork()){
case -1:
perror("Problem calling fork");
return -1;
case 0:
close(anon_pipe[1]);
read(anon_pipe[0],value_price,100);
price+=10;
sprintf(value_price,"%d \n",price);
printf("Price: %d\n",atoi(value_price));
write(anon_pipe[1],value_price,sizeof(value_price));
_exit(0);
}
}
close(anon_pipe[0]);
sleep(1);
close(anon_pipe[1]);
}
return 0;
}
Beachten Sie, dass wir [Dokumentation] (http: // stackoverflow.com/documentation/posix/8082/pipes/26063/connecting-two-kind-processes-via-a-pipe # t = 201612081850028838105) zum Einrichten der Kind-Kind-Datenübertragung über eine Pipe. –