如何在Ruby和其他语言之间共享文本文件(或互斥/信号量)

How to share text file (or a mutex/semaphore) between Ruby and another language?

本文关键字:文件 信号量 文本 共享 Ruby 其他 之间 语言      更新时间:2023-10-16

我有一个C++程序,它正在将数据写入一个名为"history.txt"的文本文件。我希望它能连续写入,除非我的Ruby进程决定要从中读取。

这个问题的解决方案显然是互斥,但我只发现了用同一语言编写的进程之间共享互斥的例子。

我是否必须在两个进程之间使用命名管道来笨拙地实现这一点,或者有更简单的方法吗?

您应该能够通过在Ruby和C++中使用flock锁定"history.txt"来实现您想要的目标(这可能也存在于许多其他语言中,因为它是一个系统调用),尽管在使用此方法时可能会出现一些问题。

这是我用来测试该方法的代码。

这是Ruby代码:

File.open("history.txt", "r+") do |file|
    puts "before the lock"
    file.flock(File::LOCK_EX)
    puts "Locking until you press enter"
    gets
    puts file.gets
    file.flock(File::LOCK_UN)
end

这是C++代码:

#include <iostream>
#include <fstream>
#include <sys/file.h>
int main()
{
    FILE *h; 
    h = fopen("history.txt","a"); //open the file
    std::cout << "Press enter to lockn";
    std::cin.get();
    int hNum = fileno(h); //get the file handle from the FILE*
    int rt = flock(hNum, LOCK_EX); //Lock it down!
    std::cout << "Writing!"<<rt<<"n";
    fprintf(h,"Shoop da woop!n");
    std::cout << "Press enter to unlockn";
    std::cin.get();
    rt = flock(hNum, LOCK_UN);
    fflush(h);
    fclose(h);
    return 0;
}

通过运行这两种方法,您可以确认当C++进程锁定文件时Ruby进程停止,反之亦然。