C 语言中的 fopen/fread/fgets PID 安全吗?
各种用户正在浏览 100% 用 C (CGI) 编程的网站。每个网页都使用 fopen/fgets/fread 从文件中读取通用数据(如导航栏)。如果不同的人浏览同一页面,每个对 fopen/fgets/fread 的调用是否会互相干扰?如果是这样,在 C 中如何解决这个问题? (这是一个Linux服务器,编译是用gcc完成的,这是一个用C语言编写的CGI网站。)
示例:
FILE *DATAFILE = fopen(PATH, "r");
if ( DATAFILE != NULL )
{
while ( fgets( LINE, BUFFER, DATAFILE ) )
{
/* do something */
}
}
Various users are browsing through a website 100% programmed in C (CGI). Each webpage uses fopen/fgets/fread to read common data (like navigation bars) from files. Would each call to fopen/fgets/fread interefere with each other if various people are browsing the same page ? If so, how can this be solved in C ? (This is a Linux server, compiling is done with gcc and this is for a CGI website programmed in C.)
Example:
FILE *DATAFILE = fopen(PATH, "r");
if ( DATAFILE != NULL )
{
while ( fgets( LINE, BUFFER, DATAFILE ) )
{
/* do something */
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 Linux 上,多个进程同时读取文件是完全安全的。
On Linux, it's perfectly safe for multiple processes to simultaneously read from a file.
从多个进程(在任何现代系统中)读取数据是完全安全的。
对 fopen() 的调用返回一个指向 FILE 结构的指针,该结构有自己的成员,如标志、当前位置等。
您应该只关心是否有人更改文件(例如:收缩),而其他人正在读取它。但我想这不是你的情况。
It's perfectly safe to read from multiple processes (in any modern system).
A call to fopen() returns a pointer to a FILE structure, which has its own members, like flags, current position, etc.
You should only care if somebody changes the file (e.g: shrink), while others are reading it. But I imagine this isn't your case.
从文件中并发读取(无论是从多个线程——假设从单独打开的描述符——还是从多个进程)在所有现代主要操作系统上都是明确定义和允许的。它只是并发写入到一个定义不明确的文件,并且您不应该尝试在没有锁定的情况下执行该操作(除非您像日志一样附加到该文件,并且操作系统进行此类并发写入明确定义)。
Concurrent reads from a file (whether from multiple threads -- assuming from separately opened descriptors -- or from multiple processes) is well-defined and permitted on all modern major operating systems. It is only concurrent writes to a file which are ill-defined and which you should not attempt to do without locking (unless you are appending to the file, like a log, and the OS makes such concurrent writes well-defined).