Hot code replacement in erlang

前端 未结 4 2262
栀梦
栀梦 2020-12-23 10:59

I am working on my first real project in erlang, however, this code is simplified for brevity. I want to be able to load a newer version of a file into my project r

4条回答
  •  不知归路
    2020-12-23 11:05

    For the sake of having an explicit answer, I am posting this.

    Using @rvirding's suggestion of using the code module, I've modified it to look like this:

    -module(reloading).
    
    -export([loop/0]).
    
    loop() ->
        receive
            upgrade ->
                code:purge(?MODULE),
                compile:file(?MODULE),
                code:load_file(?MODULE),
                ?MODULE:loop();
            hello ->
                io:format("This is a test~n"),
                loop();
            _ ->
                loop()
        end.
    

    First code:purge the old ?MODULE, then compile:file the new file, and finally, code:load_file the new ?MODULE. This works as I originally intended.

    $ erl
    Erlang R15B01 (erts-5.9.1) [source] [64-bit] [async-threads:0] [hipe] [kernel-poll:false]
    
    Eshell V5.9.1  (abort with ^G)
    1> Loop = spawn(reloading, loop, []).
    <0.34.0>
    2> Loop ! hello.
    This is a test
    hello
    

    Change line to io:format("I have changed this!~n"),

    3> Loop ! upgrade.                   
    upgrade
    4> Loop ! hello.  
    I have changed this!
    hello
    

提交回复
热议问题