Unix 線程共用建立進程開啟的檔案資源(1)

來源:互聯網
上載者:User

標籤:eric   color   clu   libc   world   void   開啟   roc   線程   

執行環境:Linux ubuntu 4.4.0-31-generic #50-Ubuntu SMP Wed Jul 13 00:07:12 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux

1. 測試代碼 : a.c

 1 #include <fcntl.h> 2 #include <unistd.h> 3 #include <stdio.h> 4 #include <pthread.h> 5 #include <string.h> 6  7 pthread_t ntid; 8  9 void * thr_fn(void * arg)10 {11    int * fp = (int *)arg;12    char * str = "Hello the world!\n";13 14    int len = write(*fp,str,strlen(str));15    if(len)16    {17     printf("Thread write a string to the file by the descriptor the createprocess created!\n");18    }19 20    close(*fp);21    return ((void *)0);22 }23 24 int main(void)25 {26     int err;27     int fd;28 29     fd = open("log.txt",O_CREAT|O_WRONLY);30     if(-1 == fd)31     {32     printf("Failed to open  file!\n");33     }34 35     err = pthread_create(&ntid,NULL,thr_fn,&fd);36     if(err != 0)37     {38     printf("can‘t create thread ,errno = %d\n",err);    39     }40     sleep(3);41     return 0;42 }

 

2. 如果系統沒有相應的pthread庫,執行:

 1 sudo apt-get install glibc-doc

 2 sudo apt-get install manpages-posix-dev 

 編譯運行:

 1 gcc a.c -lpthread 

 

Unix 線程共用建立進程開啟的檔案資源(1)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.