Hot code replacement in erlang

前端 未结 4 2252
栀梦
栀梦 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
    
    0 讨论(0)
  • 2020-12-23 11:08

    In addition to the above I'd like to notice that some tools that reload code automatically for you exist.

    You should have a look at sync or active projects.

    0 讨论(0)
  • 2020-12-23 11:18

    While erlang can handle two versions of a module and calling a function with mod:func(...) will always call the latest version of a module (if the function is exported) you still have to load the new version of the module into Erlang system. You can't expect it automagically detect that you happen to have a new version of the module somewhere, find it, compile it and load it.

    N.B. compiling and loading are two separate things. So c(mod). both compiles and loads the module, while l(mod). just loads the object code (.beam file) of the already compiled module. The Erlang compiler is called from the module compile and it just compiles and generates a .beam file while the code loading is handled by the module code.

    0 讨论(0)
  • 2020-12-23 11:24

    Compile *.beam locally, then send it to your server and reload it as mentioned in man pages:

    http://erlang.org/documentation/doc-1/reference_manual/code_loading.html#id86381

    -module(m).
    -export([loop/0]).
    
    loop() ->
        receive
            code_switch ->
                m:loop();
            Msg ->
                ...
                loop()
        end.
    
    0 讨论(0)
提交回复
热议问题