Linux Web 服务器并发文件处理 (read/write)

Linux Webserver concurrent file handling (read/write)

希望您能就我的问题给我一些建议。

我得到的是 Raspberry Pi 上的 Web 服务器 运行。在上面,C 程序在一定的时间间隔(1 秒)内写入 JPEG 文件,如下所示:

fout = fopen("/tmp/image1.jpg", "w");
fwrite(jpgBuffer, jpgFileSize, 1, fout);
fclose(fout);

我通过网络浏览器访问图像:“192.168.178.xxx/tmp/image1.jpg” 大多数情况下,图像会完美显示。但是有时我会在图像中看到伪影。

我的假设是,文件是在我从网络浏览器请求图像期间写入的。我怎样才能避免这种行为?或者我如何确保在请求期间打开文件进行读取时不写入文件。

我阅读了有关文件锁定的内容,但不确定这是否可行。我知道我可以在写入文件之前使用 flock 函数设置排他锁,然后再解锁。但我还读到相应的文件打开功能必须设置读取或共享锁才能使此方法起作用。但是我不知道我通过网络浏览器发出的http请求是否设置了这样的读锁。

如有任何建议,我们将不胜感激。

非常感谢!

写入另一个临时文件,然后将其重命名为“/tmp/image1.jpg”。鉴于 renamepretty atomic,您的问题可能会得到解决。

一种可能的替代方法是使用 mandatory locks: the writing process sets the RW lock after opening the file for reading and writing, then the kernel will block the web server from reading the file until the lock is removed (either explicitly or implicitly when the writing process exits). However, this approach involves additional steps (filesystem must be mounted with the "mand" option, group setgid attribute must be set by "g+s", also "g-x"), also, usage of mandatory locks in linux is frowned upon