[erlang-questions] escript vs erl
Jachym Holecek
freza@REDACTED
Thu Feb 24 00:41:42 CET 2011
# Andrew Pennebaker 2011-02-23:
> When I run my Erlang scripts with escript, threads throw an undef error when
> trying to call themselves recursively.
>
> E.g.
>
> loop() ->
> io:format("Looping~n"),
>
> receive
> after
> 3 -> loop()
> end.
>
> main(_) ->
> spawn(loop, loop, []).
>
> $ escript loop.erl
>
> =ERROR REPORT==== 23-Feb-2011::17:18:05 ===
> Error in process <0.30.0> with exit value: {undef,[{loop,loop,[]}]}
Correct -- your escript is interpreted by module erl_eval, there's no loop
module. You can use spawn(fun () -> loop() end) instead. One would naively
assume this is identical to spawn(fun loop/0) under any conditions, but it
turns out it's not (because erl_eval "Don't know what to do...", to quote
the source).
Other problem with your code is that the escript will terminate as soon as
main/0 terminates, which may very well be before your new process even has
a chance to enjoy its first timeslice (you're probably aware of that, so just
for completeness' sake).
> The mitigation is to run erl and compile loop.erl into loop.beam before
> running.
>
> $ erl
> 1> c(loop).
> 2> q().
> $ escript loop.erl
> Looping
> Looping
> Looping
> ...
You can also enforce script compilation with -mode(compile) attribute, or
make an escript out of a precompiled BEAM file directly (others will know
the precise procedure for this off the top of their heads -- it's really
simple, but I forgot).
I think both of these are the best solution to your problem -- this way
your script will behave just the same as "normal" Erlang code.
> Could Erlang be modified so that recursive functions work interactively with
> escript, rather than requiring explicit compilation first?
The problem isn't with recursive functions but with remote function refs.
Without looking closer I suspect making interpreted modules behave like
real modules could be quite a bit of work -- and personally I'd think it
wouldn't be worth the trouble; current behaviour is perhaps initially
confusing but in the end makes sense... but that's just me, anyway.
Regards,
-- Jachym
More information about the erlang-questions
mailing list