linux 下多线程给文件加排他锁
利用flock 函数,具体用户请自己查。
执行流程
1,创建 /dev/shm/test文件,并打开文件。
2,fork 一个子进程
在子进程中再次打开文件,目的是不和父进程使用不一样的文件描述符。
3,父子进程各自给文件加排他锁并sleep10秒,
然后向文件中写入数据。
代码如下
1 /*slock.c*/
2 #include
3 #include
4 #include
5 #include
6 #include
7 #include
8 intmain()9 {10
11 int fd = open( "/dev/shm/test",O_CREAT|O_RDWR,S_IRWXU|S_IRGRP|S_IWGRP|S_IRWXO );12 if ( fd < 0)13 {14 puts( "open error");15 return -1;16 }17 if (fork () == 0) {18 int fd1 = open( "/dev/shm/test",O_RDWR);19 if(flock(fd1,LOCK_EX)==0){20 printf("pid(%d) %s",getpid(), "the file was locked by child .\n");21 puts( "child sleep now ...");22 sleep( 10);23 write(fd, "child\n",strlen("child\n"));24 if(flock(fd1,LOCK_UN)==0){25 puts("child the file was unlocked .\n");26 }27 }28 close( fd1);29 puts( "child exit...");30
31 } else{32 if(flock(fd,LOCK_EX)==0){33 printf("pid(%d) %s",getpid(), "the file was locked by parent .\n");34 puts( "parent sleep now ...");35 sleep( 10);36 write(fd, "parent\n",strlen("parent\n"));37 if(flock(fd,LOCK_UN)==0){38 puts("parent the file was unlocked .\n");39 }40 }41
42 puts( "parent exit...");43 close( fd );44 }45 return 0;46 }
执行结果
[[email protected]]# ./slockc
pid(1516) the file was locked by parent .
parent sleep now ...
parent the file was unlocked .
parent exit...
[[email protected]]# pid(1517) the file was locked by child .
child sleep now ...
child the file was unlocked .
child exit...
最后查看 /dev/shm/test内容
parent
child
原文:http://www.cnblogs.com/snail88/p/7727236.html