协调两个程序对同一文件的读写操作?

huangapple 未分类评论47阅读模式
英文:

Coordinate two programs that read/write the same file?

问题

我有两个需要通信的单独程序:一个是 PHP 程序,另一个是 Java 守护进程。PHP 程序将命令写入日志文件中,Java 守护进程读取这些命令并执行,然后清空日志。

这种方法大约有 2/3 的时间能够正常工作。

我认为问题可能在于 PHP 有时会在 Java 守护进程正在读取或执行命令的过程中写入新的命令。这意味着当守护进程执行清空命令的操作时,它会把 PHP 的新命令一并清除,而不执行它们。

有没有更可靠的方法来构建结构,以确保来自 PHP 的新命令不会与旧命令一起被清除?

英文:

I have two separate programs that need to communicate: a PHP program and a Java daemon. The PHP program writes commands to a log file. The Java daemon reads them, executes them, and clears the log.

This works about 2/3 of the time.

I think the problem is that PHP is sometimes writing commands while the Java daemon is in the middle of reading or executing commands. That means that when it gets to the stage of clearing the commands, it erases the new commands from PHP without ever executing them.

Is there a more sound way to structure things so that I make sure that new commands from PHP don't get erased along with the old commands?

答案1

得分: 0

这是日志文件轮转常见的问题,其中使用的模式可以直接应用于这种情况。

请不要从外部进程中截断文件,那几乎肯定会导致数据丢失。相反,让 PHP 定期关闭它正在写入的文件,并切换到写入新文件。

Java 进程读取文件可以通过定期列出目录内容,或者通过使用 FileWatcher API 订阅文件创建事件来检测 PHP 是否已切换到另一个文件。

另一个选项是让 PHP 进程向文件写入“嘿,我要切换到另一个文件”的消息,并在 Java 进程读取此消息时切换文件。

英文:

This is a common problem with log file rotation, and the patterns used there can be applied to this situation directly.

Don't truncate the file from the external process, that is almost guaranteed to lead to data loss. Instead, make PHP periodically close the file it's writing, and switch to writing to a new file.

The Java process reading the file may detect that PHP has switched to another file by listing the directory contents at regular intervals, or by subscribing to file creation events with the FileWatcher API.

Another option is to make the PHP process write a "hey I'm switching to this other file" message to the file, and make the Java process switch files when it reads this message.

huangapple
  • 本文由 发表于 2020年7月27日 04:15:08
  • 转载请务必保留本文链接:https://java.coder-hub.com/63105234.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定