fopen问题,求教高手

doc110 2011-10-28 01:00:38
fopen打开一个文件的时候,为什么其他应用程序还可以打开。
比如我程序打开了一个文件,用计事本还是可以打开这个文件,fopen的打开方式不是是独享的吗?
为什么会出现这种情况,请高手解答。
...全文
133 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq120848369 2011-10-28
  • 打赏
  • 举报
回复
一个文件多个进程打开当然可以,只是使用的是不同的文件表项(包括当前文件指针偏移量),但实际操作还是落在同一个文件上。

如果想多进程共同操作一个文件,建议使用O_APPEND追加写+文件锁,写之前对整个文件加锁。

文件锁只是方便一点,其他各种锁你都可以用,只要是进程间共享的锁(信号量,prc_shared互斥锁)。(看下边说明,默认追加写是原子操作,除了NFS,所以如果不是NFS,可以不用锁。)

以下摘自linux:

   Advisory locking
F_GETLK, F_SETLK and F_SETLKW are used to acquire, release, and test for the existence of record locks (also known as file-segment or file-region
locks). The third argument, lock, is a pointer to a structure that has at least the following fields (in unspecified order).

struct flock {
...
short l_type; /* Type of lock: F_RDLCK,
F_WRLCK, F_UNLCK */
short l_whence; /* How to interpret l_start:
SEEK_SET, SEEK_CUR, SEEK_END */
off_t l_start; /* Starting offset for lock */
off_t l_len; /* Number of bytes to lock */
pid_t l_pid; /* PID of process blocking our lock
(F_GETLK only) */
...
};

       O_APPEND
The file is opened in append mode. Before each write(2), the file offset is positioned at the end of the file, as if with lseek(2).
O_APPEND may lead to corrupted files on NFS file systems if more than one process appends data to a file at once. This is because NFS does
not support appending to a file, so the client kernel has to simulate it, which can't be done without a race condition.

luciferisnotsatan 2011-10-28
  • 打赏
  • 举报
回复
CreateFile
OpenFile
用这两个函数吧

64,676

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧