新创建线程和主线程会共享地址空间,但在实际执行中各自都有独立的task_struct。那么在pthread_create一个新线程之后,如果主线程再打开一个文件,原有线程是否可以用主线程的句柄读写文件呢。一般来说通过文件句柄来读写文件遵循下面的流程通过对sys_clone的分析应该是可以的,下面验证一下:
1.源码
#include<stdlib.h>
#include<stdio.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int iOpenFd = -1;
char *str = "Hello World";
void *func(void *arg)
{
while(1)
{
sleep(2);
if(iOpenFd < 0)
{
printf("thread says:openfd < 0\n");
continue;
}
write(iOpenFd , str , strlen(str));
printf("done\n");
}
return 0;
}
int main(int argc , char **argv)
{
int ifd = -1;
pthread_t tid;
if(pthread_create(&tid , NULL , func , NULL) < 0)
{
printf("create thread failed!\n");
return -1;
}
sleep(4);
printf("try to open thread.info\n");
ifd = open("./thread.info" , O_RDWR|O_APPEND);
if(ifd < 0)
{
printf("open failed!\n");
return -1;
}
printf("open success!\n");
iOpenFd = ifd;
pause();
return 0;
}
iOpenFd再创建一个新线程