作者:一恒谢永泰_661 | 来源:互联网 | 2023-09-13 15:55
执行环境:Linuxubuntu4.4.0-31-generic#50-UbuntuSMPWedJul1300:07:12UTC2016x86_64x86_64x86_64
执行环境: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
2 #include
3 #include
4 #include
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