jackdharma1994

Untitled

Jun 27th, 2015
219
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.13 KB | None | 0 0
  1. /*
  2.     Realizzare un programma C e Posix sotto Linux che con l'uso
  3.     dei semafori Posix sincronizzi un processo padre ed un
  4.     processo figlio che scrivono e leggono, rispettivamente, un
  5.     numero intero alla volta  da 1 a n, (dove n è passato da riga di
  6.     comando) nella prima posizione di un file temporaneo
  7.     opportunamente creato  
  8. */
  9. #include <stdlib.h>
  10. #include <stdio.h>
  11. #include <unistd.h>
  12. #include <semaphore.h>
  13. #include <sys/types.h>
  14. #include <sys/stat.h>
  15. #include <fcntl.h>
  16. #define N 9
  17. sem_t sem1,sem2;
  18.  
  19. int main(int arg, char **argv){
  20.    
  21.    
  22.     int pid,file,i=4;
  23.     char buff[2];
  24.  
  25.     sem_init(&sem1,1,1);
  26.     sem_init(&sem2,1,0);
  27.    
  28.     //file = open("file.txt",O_RDWR);
  29.  
  30.     pid = fork();
  31.    
  32.     if (pid==0){
  33.         for(i=0;i<N;i++) {
  34.             sem_wait(&sem1);
  35.             //sprintf(&buff[0],"%d",i);
  36.             //lseek(file, 0, SEEK_SET);
  37.             //write(file,&buff,sizeof(buff));
  38.             printf("Ho scritto i=%d\n",i);
  39.             sem_post(&sem2);
  40.            
  41.         }
  42.        
  43.     } else {
  44.         for(i=0;i<N;i++) {
  45.             sem_wait(&sem2);
  46.             //lseek(file, 0, SEEK_SET);    
  47.             //read(file,&buff,sizeof(buff));
  48.             printf("Ok ho letto %d\n",atoi(&buff[0]));
  49.             i++;
  50.             sem_post(&sem1);
  51.         }
  52.    
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment