linux 下多線程寫檔案

來源:互聯網
上載者:User

標籤: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 下多線程寫檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.