Zaibon

Untitled

Aug 9th, 2012
228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.64 KB | None | 0 0
  1. #include <unistd.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <sys/types.h>
  5. #include <sys/stat.h>
  6. #include <fcntl.h>
  7.  
  8. void sortieErreur(char*);
  9.  
  10. int rc;
  11. char buff[50];
  12.  
  13. int main(){
  14.  
  15.     int idFils;
  16.     struct flock lock;
  17.     int fd,fd2;
  18.  
  19.     if( (fd = open("test.txt",O_RDWR|O_TRUNC)) == -1){
  20.         sortieErreur("ouverture fichier");
  21.     }
  22.  
  23.     if( write(fd, "1234567890", 10) == -1)
  24.         sortieErreur("erreur write");
  25.  
  26.     if( (idFils = fork()) == -1)
  27.         sortieErreur("erreur fork");
  28.    
  29.     if(idFils == 0){
  30.         //processus fils
  31.        
  32.         if( (fd2 = open("test.txt",O_RDWR)) == -1){
  33.         sortieErreur("ouverture fichier");
  34.         }
  35.        
  36.         sleep(1);
  37.         printf("\t(fils) debut\n");
  38.  
  39.         printf("\t(fils) tentative de lecture\n");
  40.         if( lseek(fd2, 0, SEEK_SET) == -1)
  41.             sortieErreur("erreur lseek");
  42.         if( (rc = read(fd2, buff,10)) == -1)
  43.             sortieErreur("erreur read");
  44.         // if( (rc = write(fd2, "abcedfghty",10)) == -1)
  45.         //  sortieErreur("erreur write");
  46.  
  47.         printf("\t(fils)caractere lu %d\n",rc);
  48.         buff[rc] = '\0';
  49.         printf("\t(fils)lecture : %s\n", buff);
  50.  
  51.         if(close(fd2) == -1)
  52.             sortieErreur("erreur close");
  53.  
  54.         exit(EXIT_SUCCESS);
  55.     }else{
  56.  
  57.    
  58.     // pere
  59.     printf("(pere)debut\n" );
  60.     /*pose de verrous*/
  61.     lock.l_type = F_WRLCK;
  62.     lock.l_whence = SEEK_SET;
  63.     lock.l_start = 0;
  64.     lock.l_len = 10;
  65.     if(fcntl(fd, F_SETLK,&lock) == -1)
  66.         sortieErreur("erreur pose de verrous en lecture");
  67.  
  68.     printf("(pere) verrous posé.\n(pere)sleep 5 secondes\n");
  69.     sleep(5);
  70.  
  71.     lock.l_type = F_UNLCK;
  72.     if(fcntl(fd, F_SETLKW,&lock) == -1)
  73.         sortieErreur("erreur deverouillage");
  74.     printf("(pere) verrous enlevé\n");
  75.     }
  76.  
  77.    
  78.     if(close(fd) == -1)
  79.         sortieErreur("erreur close");
  80.  
  81.    
  82. }
  83.  
  84. void sortieErreur(char* msg){
  85.     perror(msg);
  86.     exit(EXIT_FAILURE);
  87. }
Advertisement
Add Comment
Please, Sign In to add comment