加锁与解锁
/* 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);
}
/*
jiang@jiang-linux:~/unixprog/2011322$ gcc lookit.c -o lookit;./lookit
parent:locked record
parent:unlocking
parent:exiting
child:locked
child:exiting
*/
父子进程相互等待,进入死锁状态
#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);
}
/*进入死锁状态了,似乎系统并不会自动检测2个死锁的。
jiang@jiang-linux:~/unixprog/2011322$ gcc deadlock.c -o deadlock.o;./deadlock.o
lock succeeded (proc 3023 )
parent sleeping
second lock succeeded (proc 3023)
second lock succeeded (proc3024)
parent sleeping
jiang@jiang-linux:~/unixprog/2011322$ second lock succeeded (proc 3024)
^C
*/