標籤: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)