码迷,mamicode.com
首页 > 编程语言 > 详细

Unix 线程共享创建进程打开的文件资源(1)

时间:2017-01-25 16:27:08      阅读:171      评论:0      收藏:0      [点我收藏+]

标签: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)

标签:eric   color   clu   libc   world   void   打开   roc   线程   

原文地址:http://www.cnblogs.com/jingjingdidunhe/p/6349525.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!