linux 下多進程寫文件


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 }

執行結果

[root@centos]# ./slockc
pid(1516) the file was locked by parent .
parent sleep now ...
parent the file was unlocked .

parent exit...
[root@centos]# pid(1517) the file was locked  by child .
child sleep now ...
child the file was unlocked .

child exit...

 

最后查看   /dev/shm/test內容

parent
child


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM