关于pthread与文件描述符

本文探讨了在创建新线程后,主线程如何共享文件描述符的问题。通过示例代码展示了即使新线程在主线程打开文件后,依然能通过共享的files_struct结构访问并读写文件。分析了在生成线程时,files_struct如何保持共享,而在生成进程时,files_struct会被复制。结论是pthread_create创建的线程与主线程共享files_struct,使得线程间能使用相同的文件句柄。
摘要由CSDN通过智能技术生成

新创建线程和主线程会共享地址空间,但在实际执行中各自都有独立的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再创建一个新线程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值