gpt4 book ai didi

c - C中的多线程目录工作

转载 作者:行者123 更新时间:2023-12-02 05:04:28 25 4
gpt4 key购买 nike

我在创建一个 C 程序时遇到了困难,该程序会将一个目录中的所有大小相加,然后递归地进入任何其他目录来执行相同的操作。

不幸的是,它会进入当前目录之上的目录并不断获取该目录的文件,直到发生段错误。有什么想法吗?

到目前为止,这是我的代码:首先是线程函数,然后是 main 中的相应部分

void *directorywork(void *path) 
{

/*some declarations here*/

size_t numbers_len = sizeof(statbuf.st_size)/sizeof(int);

dp = opendir(path);
chdir(path);

while((dirnext = readdir(dp)) != NULL)
{
stat(dirnext->d_name,&statbuf);

// passing over directories above the requested directory

if(strcmp(dirnext->d_name, ".") == 0)
{
continue;
}

if(strcmp(dirname->d_name, "..") == 0)
{
continue;
}

if(!S_ISDIR(statbuf.st_mode))
{
printf("File %s is %d bytes\n", dirnext->d_name, (int)statbuf.st_size);
pthread_mutex_lock(&crit);
fsum = sum + (int)statbuf.st_size;
pthread_mutex_unlock(&crit);
}
else
{
pthread_create(&tids[i++], NULL, directorywork, (void*)path);
i++;
}
}
}

main()中的代码:

int main(int argc, char *argv[]) {

/*some string input parsing*/

int k;

psize(NULL);

for (k = 0; k < i; k++)
{
pthread_join(tids[k], NULL);
}

printf("Total sum of all directories is: %d\n\n", fsum);

free(firstpath);
free(path);

return 0;
}

最佳答案

您设计的主要问题是工作目录是进程的属性,而不是单个线程。因此,一个线程中的 chdir 会扰乱所有其他线程。要解决此问题,您需要从每个组件构建相对或绝对路径名,或者使用 POSIX 2008 中添加的新“at”接口(interface)(openat 等`)。

关于c - C中的多线程目录工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16503121/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com