C中的多线程目录工作
问题描述:
我很难创建一个C程序,它会将目录中的所有大小相加,然后递归地进入任何其他目录来执行相同的操作。C中的多线程目录工作
不幸的是,它在当前目录上方的目录上,并一直重复获取该目录的文件,直到发生seg故障。有任何想法吗?
这是到目前为止我的代码:第一个线程函数,然后在主
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(openat
等)中添加的新“at”接口。
是的 - 我希望开发人员停止使用'工作目录'。 – 2013-05-12 09:59:07
工作目录应该真正被当作程序的只读输入,因此只在调用'exec'前才改变。 – 2013-05-12 12:39:29