- 8
- 0
- CPU
- Intel(R) Core(TM) i7-8750H CPU @ 2.20GHz
- RAM
- 16,0 GB
- GPU
- NVIDIA GeForce GTX 1070 with Max-Q Design
- OS
- Windows 10
Ciao! Sto studiando i processi e avevo pensato di scrivere una sorta di chat tra parent/child, ma semplificata. Fondamentalmente figlio scrive, genitore legge / genitore scrive, figlio legge.
Qui il codice:
e qui si pone il problema: dopo aver inviato/ricevuto il messaggio due volte, ovviamente la chat si arresta. Ho provato a mettere un while(true) / while(1) / for(; ;) / while(!=0) ma non è il modo giusto lol
Come posso scrivere un ciclo in maniera tale che la porzione di codice venga ripetuta fino a che qualcuno scrive?
Qui il codice:
C:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
int main(){
pid_t pid;
char string[256];
char readBuffer[80];
int fd[2];
pipe(fd);
pid = fork();
if(pid == -1){
printf("Errore creating fork.\n");
exit(1);
}
if(pid == 0){ //child process
close(fd[0]);
printf("A - Input message: ");
fgets(string, sizeof(string), stdin);
write(fd[1], string, (strlen(string)+1));
exit(0);
}else{ //parent process
close(fd[1]);
read(fd[0], readBuffer, sizeof(readBuffer));
printf("A says: %s", readBuffer);
}
pipe(fd);
pid = fork();
if(pid == -1){
printf("Errore creating fork.\n");
exit(1);
}
if(pid == 0){ //child process
close(fd[1]);
read(fd[0], readBuffer, sizeof(readBuffer));
printf("B says: %s", readBuffer);
}else{ //parent process
close(fd[0]);
printf("B - Input message: ");
fgets(string, sizeof(string), stdin);
write(fd[1], string, (strlen(string)+1));
exit(0);
return 0;
}
e qui si pone il problema: dopo aver inviato/ricevuto il messaggio due volte, ovviamente la chat si arresta. Ho provato a mettere un while(true) / while(1) / for(; ;) / while(!=0) ma non è il modo giusto lol
Come posso scrivere un ciclo in maniera tale che la porzione di codice venga ripetuta fino a che qualcuno scrive?
Ultima modifica da un moderatore: