#include #include #include #include #include #include #include void file_private_mmap() { // apro il file con open // voglio avere a disposizione il contenuto del file // sotto forma di memory map // nella virtual memory del processo int fd; struct stat sb; char * address; int bytes_to_read; fd = open("prova.txt", O_RDONLY); if (fd == -1) { perror("open"); exit(1); } if (fstat(fd, &sb) == -1) { perror("fstat"); exit(1); } printf("file size = %ld\n", sb.st_size); //bytes_to_read = sb.st_size; bytes_to_read = 3; address = mmap(NULL, bytes_to_read, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0); if (address == MAP_FAILED) { perror("mmap"); exit(1); } close(fd); //printf("provo a modificare la memory map...\n"); //address[0] = '*'; write(1, address, bytes_to_read); if (munmap(address, sb.st_size) == -1) { perror("munmap"); exit(1); } } int main() { // creiamo una memory map su file // che sia condivisa tra processo padre e processo figlio // il processo figlio modificherà questa memory map // e quando il processo figlio terminerà, il processo padre // vedrà le modifiche apportate dal processo figlio // inoltre vogliamo che le modifiche alla memory map // siano riportate al file int fd; struct stat sb; char * address; int bytes_to_read; // ipotesi: il file esiste già fd = open("prova.txt", O_RDWR); if (fd == -1) { perror("open"); exit(1); } if (fstat(fd, &sb) == -1) { perror("fstat"); exit(1); } printf("file size = %ld\n", sb.st_size); bytes_to_read = sb.st_size; address = mmap(NULL, bytes_to_read, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (address == MAP_FAILED) { perror("mmap"); exit(1); } switch (fork()) { case -1: perror("fork"); exit(1); case 0: // processo figlio address[0] = '!'; printf("[child] bye\n"); exit(0); default: if (wait(NULL) == -1) { perror("wait"); exit(1); } } // il processo padre scrive su stdout // il contenuto della memory map // vedremo le modifiche apportate dal processo figlio write(1, address, bytes_to_read); //close(fd); printf("\nbye\n"); return 0; }