我想这一点:如何检查分离属性的线程是否在退出后释放系统资源?
#include<stdio.h>
#include<pthread.h>
void * fun1(void *arg)
{
FILE *fp;
fp=fopen("data","w+");
if(fp==0)
{
perror("fopen");
return NULL;
}
perror("fopen");
fprintf(fp,"%s\n","file opened");
return NULL;
}
void main()
{
pthread_attr_t atr;
pthread_attr_init(&atr);
pthread_attr_setdetachstate(&atr,PTHREAD_CREATE_DETACHED);
pthread_t thread1;
pthread_create(&thread1,&atr,&fun1,NULL);
pthread_attr_destroy(&atr);
while(1);
}
我想知道这是否线程退出后自动或不关闭文件指针fp。
你不能检查你的代码,毕竟你是脱离了线程。假设你的空循环真的让程序继续运行,你可以从外部检查,在linux上使用['lsof'](https://linux.die.net/man/8/lsof)。 –
我提到[this](https://users.cs.cf.ac.uk/Dave.Marshall/C/node30.html#SECTION003040000000000000000),并根据说明,似乎该文件在可拆卸的情况下关闭线。 此外,您可以使用此[链接](https://stackoverflow.com/questions/12340695/how-to-check-if-a-given-file-descriptor-stored-in-a-variable-is-still -valid)来检查打开的文件描述符。 – Gaurav
@GauravPathak请注意,这说*线程资源*在分离和结束时正在释放,这与线程*使用的资源不同。不,没有文件描述符在线程结束时关闭。文件描述符表是进程内的一个*共享资源*,特定的线程拥有特定的fd而不是**。 – tofro