Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <unistd.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- void sortieErreur(char*);
- int rc;
- char buff[50];
- int main(){
- int idFils;
- struct flock lock;
- int fd,fd2;
- if( (fd = open("test.txt",O_RDWR|O_TRUNC)) == -1){
- sortieErreur("ouverture fichier");
- }
- if( write(fd, "1234567890", 10) == -1)
- sortieErreur("erreur write");
- if( (idFils = fork()) == -1)
- sortieErreur("erreur fork");
- if(idFils == 0){
- //processus fils
- if( (fd2 = open("test.txt",O_RDWR)) == -1){
- sortieErreur("ouverture fichier");
- }
- sleep(1);
- printf("\t(fils) debut\n");
- printf("\t(fils) tentative de lecture\n");
- if( lseek(fd2, 0, SEEK_SET) == -1)
- sortieErreur("erreur lseek");
- if( (rc = read(fd2, buff,10)) == -1)
- sortieErreur("erreur read");
- // if( (rc = write(fd2, "abcedfghty",10)) == -1)
- // sortieErreur("erreur write");
- printf("\t(fils)caractere lu %d\n",rc);
- buff[rc] = '\0';
- printf("\t(fils)lecture : %s\n", buff);
- if(close(fd2) == -1)
- sortieErreur("erreur close");
- exit(EXIT_SUCCESS);
- }else{
- // pere
- printf("(pere)debut\n" );
- /*pose de verrous*/
- lock.l_type = F_WRLCK;
- lock.l_whence = SEEK_SET;
- lock.l_start = 0;
- lock.l_len = 10;
- if(fcntl(fd, F_SETLK,&lock) == -1)
- sortieErreur("erreur pose de verrous en lecture");
- printf("(pere) verrous posé.\n(pere)sleep 5 secondes\n");
- sleep(5);
- lock.l_type = F_UNLCK;
- if(fcntl(fd, F_SETLKW,&lock) == -1)
- sortieErreur("erreur deverouillage");
- printf("(pere) verrous enlevé\n");
- }
- if(close(fd) == -1)
- sortieErreur("erreur close");
- }
- void sortieErreur(char* msg){
- perror(msg);
- exit(EXIT_FAILURE);
- }
Advertisement
Add Comment
Please, Sign In to add comment