加锁与解锁
/* lockit---demonstration of fcntl locking */ #include<fcntl.h> #include<unistd.h> #include<stdlib.h> #include<stdio.h> int main(void) { int fd; struct flock my_lock; /*set the parameters for the write lock*/ my_lock.l_type=F_WRLCK; my_lock.l_whence=SEEK_SET; my_lock.l_start=0; my_lock.l_len=10; /* open file */ fd=open("locktest",O_RDWR); /*lock first ten bytes */ if(fcntl(fd,F_SETLKW,&my_lock)==-1) { perror("parent:locking"); exit(1); } printf("parent:locked record /n"); switch(fork()) { case -1: perror("fork"); exit(1); case 0: my_lock.l_len=5; if(fcntl(fd,F_SETLKW,&my_lock)==-1) { perror("child:locking"); exit(1); } printf("child:locked/n"); printf("child:exiting/n"); exit(0); } sleep(5); /*now parent releases lock before exiting */ printf("parent:unlocking/n"); my_lock.l_type=F_UNLCK; if(fcntl(fd,F_SETLK,&my_lock)==-1) { perror("parent:unlocking"); exit(1); } /* now parent exiting */ printf("parent:exiting/n"); exit(0); }
#include<stdlib.h> #include<unistd.h> #include<stdio.h> #include<fcntl.h> int main(void) { int fd; struct flock first_lock; struct flock second_lock; first_lock.l_type=F_WRLCK;//write lock first_lock.l_whence=SEEK_SET; first_lock.l_start=0; first_lock.l_len=10; second_lock.l_type=F_WRLCK; second_lock.l_whence=SEEK_SET; second_lock.l_start=0; second_lock.l_len=10; fd=open("locktest",O_RDWR); if(fcntl(fd,F_SETLKW,&first_lock)==-1) { fatal("first_lock"); } printf("lock succeeded (proc %d )/n",getpid()); switch(fork()) { case -1: /*error*/ fatal("fork call"); case 0: /*child*/ if(fcntl(fd,F_SETLKW,&second_lock)==-1)//second lock { fatal("second lock"); } printf("second lock succeeded (proc%d)/n",getpid()); if(fcntl(fd,F_SETLKW,&second_lock)==-1) //first lock { fatal("second lock"); } default: /*parent*/ printf("parent sleeping/n"); sleep(5); if(fcntl(fd,F_SETLKW,&second_lock)==-1)//lock child's lock { fatal("child lock second lock:child already lock"); } printf("second lock succeeded (proc %d)/n",getpid()); } } int fatal(char *s) { perror(s); exit(1); }