Unix 线程共享创建进程打开的文件资源(1)
执行环境: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
学习记录,方便复习