Advertisement
Laendor86

Esercizio multiprocesso lettura/scrittura da file

Apr 17th, 2021
667
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.43 KB | None | 0 0
  1. #include<fcntl.h>
  2. #include<stdio.h>
  3. #include<stdlib.h>
  4. #include <unistd.h>
  5. #include <sys/types.h>
  6. #include <sys/wait.h>
  7. #include<string.h>
  8.  
  9. int* crea_file(char* filename);
  10. void scrivi_messaggio_su_file(int fd);
  11. void leggi_messaggio_da_file();
  12.  
  13.  
  14. int main(int argc, char* argv[]){
  15.     char filename[] = "ESEMPIO";
  16.     int fd, pid, rc;
  17.    
  18.     fd = *(crea_file(filename));
  19.    
  20.     if (fork()==0){
  21.         rc = open(filename,O_RDWR);
  22.         if (rc<0) fprintf(stderr,"error: opening file");
  23.        
  24.         scrivi_messaggio_su_file(fd);
  25.     } else {
  26.         rc = wait(NULL);
  27.         if (rc<0) fprintf(stderr,"error: wait");
  28.        
  29.         leggi_messaggio_da_file();
  30.     }
  31.     rc = close(fd);
  32.     if (rc<0) fprintf(stderr,"error: closing file");
  33.    
  34.     exit(0);
  35. }
  36.  
  37.  
  38. /**
  39. * Crea un nuovo file vuoto
  40. *
  41. * @param filename nome del file da creare
  42. * @return il file descrittore del file appena creato;
  43. */
  44. int *crea_file(char *filename){
  45.     int *fd = (int *) malloc(sizeof(int));
  46.     *fd = creat(filename, 0666);
  47.     return fd;
  48. }
  49.  
  50. /**
  51. * Leggi un messaggio da tastiera e scrivi su file in input
  52. * @param fd: file descrittore riferito al file su cui scrivere
  53. */
  54. void scrivi_messaggio_su_file(int fd){
  55.     int rc;
  56.    
  57.     fprintf(stdout,"Insert a message: ");
  58.     char *message;
  59.     scanf("%m[^\n]", &message);
  60.    
  61.     rc = write(fd,message, strlen(message));
  62.     if (rc<0) fprintf(stderr,"error: writing on file");
  63. }
  64.  
  65. /**
  66. * Leggi un messaggio da file appena scritto
  67. */
  68. void leggi_messaggio_da_file(){
  69. }
  70.  
  71.  
  72.  
  73.  
  74.  
  75.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement