微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何检查文件是否已经在C中打开

我正在处理一个multithreading的系统,根据文件访问权限可以在不同的线程之间共享一个文件。 我怎样才能检查文件是否已被另一个线程打开。 提前致谢

C# – closuressubprocess的inputstream

使用注入的DLL从外部应用程序渲染到OpenGL场景中

mmap物理连续的内存

什么是testing和testing驱动开发的良好在线介绍?

Unix套接字:客户端在第一条消息之后停止正确接收消息

你可以使用int flock(int fd,int operation); 将文件标记为锁定,并检查是否被锁定。

Apply or remove an advisory lock on the open file specified by fd. The argument operation is one of the following: LOCK_SH Place a shared lock. More than one process may hold a shared lock for a given file at a given time. LOCK_EX Place an exclusive lock. Only one process may hold an exclusive lock for a given file at a given time. LOCK_UN Remove an existing lock held by this process.

如果您在每个线程中分别打开文件,那么群集应该在线程应用程序中工作: 多个线程能够同时获得群集

有更多关于羊群的信息, 这里有潜在的弱点:

要找出在linux上是否已经打开了一个已命名的文件,可以扫描/proc/self/fd目录以查看该文件是否与文件描述符关联。 下面的程序勾画出一个解决方案:

DIR *d = opendir("/proc/self/fd"); if (d) { struct dirent *entry; struct dirent *result; entry = malloc(sizeof(struct dirent) + NAME_MAX + 1); result = 0; while (readdir_r(d,entry,&result) == 0) { if (result == 0) break; if (isdigit(result->d_name[0])) { char path[NAME_MAX+1]; char buf[NAME_MAX+1]; snprintf(path,sizeof(path),"/proc/self/fd/%s",result->d_name); ssize_t bytes = readlink(path,buf,sizeof(buf)); buf[bytes] = ''; if (strcmp(file_of_interest,buf) == 0) break; } } free(entry); closedir(d); if (result) return FILE_IS_FOUND; } return FILE_IS_NOT_FOUND;

从你的评论看来,你想要做的就是检索一个现有的FILE *如果已经通过以前对该文件上的fopen()调用创建的话。 标准C库没有提供任何机制来遍历所有当前打开的FILE * 。 如果有这样的机制,你可以用fileno()来得到它的文件描述符,然后用readlink()来查询/proc/self/fd/# ,如上所示。

这意味着您将需要使用数据结构来管理您打开的FILE * 。 可能是一个使用文件名作为键的散列表对你来说是最有用的。

我不太了解Windows上的多线程,但是如果你在Linux上,你有很多选择。 一个奇妙的资源。 您也可以利用操作系统本身或显式提供的任何文件锁定功能 (例如: fcntl )。 更多关于Linux锁定在这里 。 创建和手动管理自己的互斥为您提供了更大的灵活性。 user814064关于flock()的评论看起来像是完美的解决方案,但它永远不会有伤害的选择!

添加一个代码示例:

#include <stdio.h> #include <stdlib.h> #include <pthread.h> FILE *fp; int counter; pthread_mutex_t fmutex = PTHREAD_MUTEX_INITIALIZER; void *foo() { // pthread_mutex_trylock() checks if the mutex is // locked without blocking //int busy = pthread_mutex_trylock(&fmutex); // this blocks until the lock is released pthread_mutex_lock(&fmutex); fprintf(fp,"counter = %dn",counter); printf("counter = %dn",counter); counter++; pthread_mutex_unlock(&fmutex); } int main() { counter = 0; fp = fopen("threads.txt","w"); pthread_t thread1,thread2; if (pthread_create(&thread1,NULL,&foo,NULL)) printf("Error creating thread 1"); if (pthread_create(&thread2,NULL)) printf("Error creating thread 2"); pthread_join(thread1,NULL); pthread_join(thread2,NULL); fclose(fp); return 0; }

如果你倾向于在shell中做,你可以简单地使用lsof $filename 。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐