php - 当 PHP、C++ 和 shell 脚本尝试访问同一个文件时,如何避免错误?

标签 php c++ bash

在 PHP、C++ 和 bash 脚本中是否有方法可以让相应的程序在访问文件时等待轮到它?

我有一个用 PHP 编写的网页,使用户能够输入 6 个值:

URL
URL Refresh Interval
Brightness
Color1 in hex
Color2 in hex
Color3 in hex

这些值将写入configuration.txt .

每次访问网页configuration.txt打开后,PHP 从那里获取一些值,然后将其关闭。 configuration.txt当提交上述一个或多个值时也会打开,然后关闭。

接下来,我有一个定期 wgets 的 bash来自 configuration.txt 的 URL并将输出写入另一个名为 url_response.txt 的文件.

while [ 0 ]
do
    line=$(head -n 1 data/configuration.txt)
    wget -q -i $line -O url_response.txt
    sleep 2
done

此脚本将被放入 C++ 程序中。

最后,同一个 C++ 程序必须访问 url_response.txt从中获取和解析一些字符串,它还必须访问 configuration.txt从中获取三种颜色。

我很确定这 3 个程序会在一点交叉,我不想知道那时会发生什么。

最佳答案

避免竞争条件的常用方法是使用锁定文件。当程序尝试读取或写入 configuration.txt 时,它首先检查锁定文件。

锁有两种:

  • 共享锁
  • 独占锁

一个程序可以获得一个共享锁(读锁),只要没有其他程序有独占锁。这是用来读取文件的。只要没有其他程序写入该文件,多个程序就可以读取该文件。

只有在没有其他程序拥有锁(既非独占也非共享)的情况下,一个程序才能获得独占锁(写锁)。这用于写入文件。只要程序正在读取或写入文件,就不允许其他程序写入。

在 linux 系统上,您可以使用 flock 来管理文件锁。

阅读:

flock --shared lockfile -c read.sh

flock --exclusive lockfile -c write.sh

通常这个命令会等到锁可用。与

flock --nonblock 锁文件

命令将立即失败而不是等待。

来自手册页

SYNOPSIS

   flock [options] <file|directory> <command> [command args]
   flock [options] <file|directory> -c <command>
   flock [options] <file descriptor number>

DESCRIPTION

This utility manages flock(2) locks from within shell scripts or the command line.

The first and second forms wrap the lock around the executing a command, in a manner similar to su(1) or newgrp(1). It locks a specified file or directory, which is created (assuming appropriate permissions), if it does not already exist. By default, if the lock cannot be immediately acquired, flock waits until the lock is available.

The third form uses open file by file descriptor number. See examples how that can be used.

Here是 c++ 和 here 的联机帮助页是 shell 脚本的联机帮助页。

关于php - 当 PHP、C++ 和 shell 脚本尝试访问同一个文件时,如何避免错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57790149/

相关文章:

c++ - 警告 C4661 :no suitable definition provided for explicit template instantiation request

c++ - boost::shared_ptr 与 vector 一起使用很慢?

bash - 将变量从 bash 传递到 awk

Bash:如何使用 bash 减去两个时间字符串?

javascript - 如何在不刷新整个页面的情况下更新 HTML 文档中的 php 变量?

php - 尝试从 mysql 查询写入 Php fwrite XML 文件

c++ - 将 std::vector<boost::shared_ptr<T>> 转换为 std::vector<T*> 的优雅解决方案

bash - 将 jps 输出解析为数组

javascript - 使用 jQuery.get() 从 javascript 调用 php 文件,php 的位置?

php - 使用 php 在 MySQL 中导入大型 CSV 文件