標籤:types file string 寫入 main shm log unlock nbsp
linux 下多線程給檔案加獨佔鎖定
利用flock 函數,具體使用者請自己查。
執行流程
1,建立 /dev/shm/test檔案,並開啟檔案。
2,fork 一個子進程
在子進程中再次開啟檔案,目的是不和父進程使用不一樣的檔案描述符。
3,父子進程各自給檔案加獨佔鎖定並sleep10秒,
然後向檔案中寫入資料。
代碼如下
1 /* slock.c */ 2 #include <unistd.h> 3 #include <fcntl.h> 4 #include <sys/types.h> 5 #include <sys/stat.h> 6 #include <string.h> 7 #include <stdio.h> 8 int main() 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
linux 下多線程寫檔案