加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在ruby脚本和正在运行的c程序之间进行通信

发布时间:2020-12-17 03:43:52 所属栏目:百科 来源:网络整理
导读:我有一个执行一个功能的c程序.它将一个大型数据文件加载到一个数组中,接收一个整数数组并在该数组中执行查找,返回一个整数.我目前正在调用程序,每个整数作为参数,如下所示: $./myprogram 1 2 3 4 5 6 7 我也有一个ruby脚本,我希望这个脚本能够使用c程序. 目
我有一个执行一个功能的c程序.它将一个大型数据文件加载到一个数组中,接收一个整数数组并在该数组中执行查找,返回一个整数.我目前正在调用程序,每个整数作为参数,如下所示:

$./myprogram 1 2 3 4 5 6 7

我也有一个ruby脚本,我希望这个脚本能够使用c程序.
目前,我这样做.

Ruby代码:

arguments = "1 2 3 4 5 6 7"
an_integer = %x{ ./myprogram #{arguemnts} }
puts "The program returned #{an_integer}" #=> The program returned 2283

这一切都运行正常,但我的问题是每次ruby进行此调用时,c程序必须重新加载数据文件(超过100mb) – 非常慢,效率非常低.

如何重写我的c程序只加载一次文件,允许我通过ruby脚本进行多次查找,而不必每次都重新加载文件.使用套接字是一种明智的方法吗?将c程序编写为ruby扩展名?

显然我不是一位经验丰富的c程序员,所以感谢你的帮助.

解决方法

一种可能的方法是修改您的C程序,使其从标准输入流(std :: cin)而不是命令行参数获取其输入,并通过标准输出(std :: cout)返回其结果,而不是作为主要的回报值.然后,您的Ruby脚本将使用popen启动C程序.

假设C程序目前看起来像:

// *pseudo* code
int main(int argc,char* argv[])
{
    large_data_file = expensive_operation();

    std::vector<int> input = as_ints(argc,argv);
    int result = make_the_computation(large_data_file,input);

    return result;
}

它会转变成类似的东西:

// *pseudo* code
int main(int argc,char* argv[])
{
    large_data_file = expensive_operation();

    std::string input_line;
    // Read a line from standard input
    while(std:::getline(std::cin,input_line)){
        std::vector<int> input = tokenize_as_ints(input_line);
        int result = make_the_computation(large_data_file,input);

        //Write result on standard output
        std::cout << result << std::endl;
    }

    return 0;
}

而Ruby脚本看起来就像

io = IO.popen("./myprogram","rw")
while i_have_stuff_to_compute
    arguments = get_arguments()
    # Write arguments on the program's input stream
    IO.puts(arguments)
    # Read reply from the program's output stream
    result = IO.readline().to_i();
end

io.close()

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读