【问题标题】:How to share text file (or a mutex/semaphore) between Ruby and another language?如何在 Ruby 和另一种语言之间共享文本文件(或互斥体/信号量)?
【发布时间】:2013-08-13 02:25:16
【问题描述】:

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

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

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

【问题讨论】:

    标签: c++ ruby mutex inter-process-communicat


    【解决方案1】:

    您应该能够通过在RubyC++ 中使用flock 锁定“history.txt”来完成您想要的(这可能也存在于许多其他语言中,因为它是一个系统调用),尽管在使用此方法时似乎确实会出现一些gotchas

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

    这是 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 lock\n";
        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 unlock\n";
        std::cin.get();
        rt = flock(hNum, LOCK_UN);
        fflush(h);
        fclose(h);
        return 0;
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-20
      • 1970-01-01
      • 2011-04-10
      • 1970-01-01
      • 2011-04-20
      • 1970-01-01
      • 2013-12-17
      相关资源
      最近更新 更多