简体   繁体   English

用c / c ++锁定linux中的文件

[英]Locking files in linux with c/c++

I am wondering if you can : lock only a line or a single character in a file in linux and the rest of the file should remain accessible for other processes? 我想知道你是否可以:在linux中的文件中只锁定一行或一个字符,其他文件的其余部分应该可以访问吗? I received a task regarding simulating transaction on a file with c/c++ under linux . 我收到了一个关于在linux下使用c / c ++模拟文件上的事务的任务。 Please give me an answer and if this answer is yes ,give me some links from where i could take a peek to make this task. 请给我一个答案,如果答案是肯定的,请给我一些链接,我可以从中查看完成此任务。

Thanks, Madicemickael 谢谢,Madicemickael

fcntl() is the one API to choose, since it is the least broken and is POSIX. fcntl()是一个可供选择的API,因为它是最少破坏的并且是POSIX。 It is the only one that works across NFS. 它是唯一一个跨NFS工作的。 That said it is a complete disaster, too, since locks are bound to processes, not file descriptors. 这也说是一场彻底的灾难,因为锁被绑定到进程,而不是文件描述符。 That means that if you lock a file and then some other thread or some library function locks/unlocks it, your lock will be broken too. 这意味着如果您锁定一个文件,然后某个其他线程或某些库函数锁定/解锁它,您的锁也将被破坏。 Also, you cannot use file system locks to protect two threads of the same process to interfere with each other. 此外,您不能使用文件系统锁来保护同一进程的两个线程相互干扰。 Also, you should not use file locks on files that are accessible to more than one user, because that effectively enables users to freeze each others processes. 此外,您不应对多个用户可访问的文件使用文件锁,因为这样可以有效地使用户冻结彼此的进程。

In summary: file locking on Unix creates more problems than it solves. 总结:Unix上的文件锁定会产生比它解决的问题更多的问题。 Before you use it you need to be really sure you fully understand the semantics. 在你使用它,你需要真正确保你完全理解的语义。

Yes, this is possible. 是的,这是可能的。

The Unix way to do this is via fcntl or lockf . Unix的方法是通过fcntllockf Whatever you choose, make sure to use only it and not mix the two. 无论你选择什么,一定要只使用它而不要混合两者。 Have a look at this question (with answer) about it: fcntl, lockf, which is better to use for file locking? 看看这个问题(有答案): fcntl,lockf,哪个更好用于文件锁定? .

If you can, have a look at section 14.3 in Advanced Programming in the UNIX Environment . 如果可以,请查看UNIX环境中高级编程的第14.3节。

lockf(3)可以将锁应用于文件的一部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM