Using os:cmd to in escript to start Erlang application fails. - erlang

I have an Erlang application named tb that runs fine from Erlang command line by doing application:start(tb). Whereas when I try to invoke the same application from inside escript using os:cmd, the application doesn't seem to run. When i do a 'ps | grep beam', I see the beam.smp process running. But the application is not generating any output.What might be the problem? Is there a better way to start another erlang VM from inside escript?
Here's the code snippet:
net_kernel:start([tb_escript, shortnames]),
read_config_file(FName),
Cookie = get(cookie),
Node = get(node),
N = io_lib:format("~p",[Node]),
lists:flatten(N),
C = io_lib:format("~p",[Cookie]),
lists:flatten(C),
EBIN = "~/tb/ebin",
erlang:set_cookie(tb_escript,Cookie),
os:cmd("erl -pa " ++ EBIN ++ " -sname " ++ N ++ " -detached " ++ " -setcookie " ++ C ++ " -s application start tb").

This happens because the args flag to -s wraps the arguments in a list and passes that to module:function/1. -s application start tb will execute application:start([tb]), which would return {error,{bad_application,[ssl]}}. As this is just a normal return value, no error is printed by erl.
From the erl documentation:
-s Mod [Func [Arg1, Arg2, ...]](init flag)
Makes init call the specified function. Func defaults to start. If no arguments are provided, the function is assumed to be of arity 0. Otherwise it is assumed to be of arity 1, taking the list [Arg1,Arg2,...] as argument. All arguments are passed as atoms.
There are two ways to solve this:
Use -eval "application:start(tb)", as you already mentioned in a comment.
Add a start/0 (if not already present) function to tb which calls application:start(tb), and then pass just -s tb to erl. -s with a single argument will call module:start().

Related

Pass args through rebar shell to erl?

I am using "rebar shell" to test my app. This is documented as:
Start a shell with project and deps preloaded similar to
'erl -pa ebin -pa deps/*/ebin'.
How do I add extra args to the underlying invocation of 'erl'? For
example, I want to add application specific environment variables and
run a Module/Function. I want to invoke something like:
erl -pa ebin -pa deps/*/ebin -browser_spy browser_exe "/my/dir" -run bs_example test
(and I want code:priv_dir to work as it does when using rebar shell,
which the above 'erl' command does not do).
You cannot
rebar shell does not execute erl ... command actually, but only tries to replicate its behaviour.
Actually rebar just turns yourself into the shell along with mimicking -pa by adding paths with code:add_pathz
See here for implementation details:
shell(_Config, _AppFile) ->
true = code:add_pathz(rebar_utils:ebin_dir()),
%% scan all processes for any with references to the old user and save them to
%% update later
NeedsUpdate = [Pid || Pid <- erlang:processes(),
proplists:get_value(group_leader, erlang:process_info(Pid)) == whereis(user)
],
%% terminate the current user
ok = supervisor:terminate_child(kernel_sup, user),
%% start a new shell (this also starts a new user under the correct group)
_ = user_drv:start(),
%% wait until user_drv and user have been registered (max 3 seconds)
ok = wait_until_user_started(3000),
%% set any process that had a reference to the old user's group leader to the
%% new user process
_ = [erlang:group_leader(whereis(user), Pid) || Pid <- NeedsUpdate],
%% enable error_logger's tty output
ok = error_logger:swap_handler(tty),
%% disable the simple error_logger (which may have been added multiple
%% times). removes at most the error_logger added by init and the
%% error_logger added by the tty handler
ok = remove_error_handler(3),
%% this call never returns (until user quits shell)
timer:sleep(infinity).

Erlang how to start an external script in linux

I want to run an external script and get the PID of the process (once it starts) from my erlang program. Later, I will want to send TERM signal to that PID from erlang code. How do I do it?
I tried this
P = os:cmd("myscript &"),
io:format("Pid = ~s ~n",[P]).
It starts the script in background as expected, but I dont get the PID.
Update
I made the below script (loop.pl) for testing:
while(1){
sleep 1;
}
Then tried to spawn the script using open_port. The script runs OK. But, erlang:port_info/2 troughs exception:
2> Port = open_port({spawn, "perl loop.pl"}, []).
#Port<0.504>
3> {os_pid, OsPid} = erlang:port_info(Port, os_pid).
** exception error: bad argument
in function erlang:port_info/2
called as erlang:port_info(#Port<0.504>,os_pid)
I checked the script is running:
$ ps -ef | grep loop.pl
root 10357 10130 0 17:35 ? 00:00:00 perl loop.pl
You can open a port using spawn or spawn_executable, and then use erlang:port_info/2 to get its OS process ID:
1> Port = open_port({spawn, "myscript"}, PortOptions).
#Port<0.530>
2> {os_pid, OsPid} = erlang:port_info(Port, os_pid).
{os_pid,91270}
3> os:cmd("kill " ++ integer_to_list(OsPid)).
[]
Set PortOptions as appropriate for your use case.
As the last line above shows, you can use os:cmd/1 to kill the process if you wish.

How can I pass command-line arguments to a Erlang program?

I'm working on a Erlang. How can I pass command line parameters to it?
Program File-
-module(program).
-export([main/0]).
main() ->
io:fwrite("Hello, world!\n").
Compilation Command:
erlc Program.erl
Execution Command-
erl -noshell -s program main -s init stop
I need to pass arguments through execution command and want to access them inside main written in program's main.
$ cat program.erl
-module(program).
-export([main/1]).
main(Args) ->
io:format("Args: ~p\n", [Args]).
$ erlc program.erl
$ erl -noshell -s program main foo bar -s init stop
Args: [foo,bar]
$ erl -noshell -run program main foo bar -s init stop
Args: ["foo","bar"]
It is documented in erl man page.
I would recommend using escript for this purpose because it has a simpler invocation.
These are not really commandline-parameters, but if you want to use environment-variables, the os-module might help. os:getenv() gives you a list of all environment variables. os:getenv(Var) gives you the value of the variable as a string, or returns false if Var is not an environment-variable.
These env-variables should be set before you start the application.
I always use an idiom like this to start (on a bash-shell):
export PORT=8080 && erl -noshell -s program main
If you want "named" argument, with possible default values, you can use this command line (from a toy appli I made):
erl -pa "./ebin" -s lavie -noshell -detach -width 100 -height 80 -zoom 6
lavie:start does nothing more than starting an erlang application:
-module (lavie).
-export ([start/0]).
start() -> application:start(lavie).
which in turn start the application where I defined default value for parameters, here is the app.src (rebar build):
{application, lavie,
[
{description, "Le jeu de la vie selon Conway"},
{vsn, "1.3.0"},
{registered, [lavie_sup,lavie_wx,lavie_fsm,lavie_server,rule_wx]},
{applications, [
kernel,
stdlib
]},
{mod, { lavie_app, [200,50,2]}}, %% with default parameters
{env, []}
]}.
then, in the application code, you can use init:get_argument/1 to get the value associated to each option if it was defined in the command line.
-module(lavie_app).
-behaviour(application).
%% Application callbacks
-export([start/2, stop/1]).
%% ===================================================================
%% Application callbacks
%% ===================================================================
start(_StartType, [W1,H1,Z1]) ->
W = get(width,W1),
H = get(height,H1),
Z = get(zoom,Z1),
lavie_sup:start_link([W,H,Z]).
stop(_State) ->
% init:stop().
ok.
get(Name,Def) ->
case init:get_argument(Name) of
{ok,[[L]]} -> list_to_integer(L);
_ -> Def
end.
Definitively more complex than #Hynek proposal, but it gives you more flexibility, and I find the command line less opaque.

Erlang command line

I need to pass two arguments to my Erlang code. it is working fine in the Erlang shell.
2> crop:fall_velocity(x,23).
21.23205124334434
but how should i run the Erlang code without the Erlang shell. like normal python,c programs.
./program_name (not passing $1 $2 arguments).
I was trying this
erl -noshell -s crop fall_velocity(x,20) -s init stop
But it is giving unexpected token error.
As documentation states, the -s passes all parameters supplied as just one list of atoms and -run does the same but as a list of strings. If you want to call arbitrary function with arbitrary parameter count and types you should use -eval:
$ erl -noshell -eval 'io:format("test\n",[]),init:stop()'
test
$
You can use escript to run Erlang scripts from the command line. In that script you should create a main function which takes an array of arguments as a string.
#!/usr/bin/env escript
main(Args) ->
io:format("Printing arguments:~n"),
lists:foreach(fun(Arg) -> io:format("Got argument: ~p~n", [Arg]) end,Args).
Output:
./escripter.erl hi what is your name 5 6 7 9
Printing arguments:
Got argument: "hi"
Got argument: "what"
Got argument: "is"
Got argument: "your"
Got argument: "name"
Got argument: "5"
Got argument: "6"
Got argument: "7"
Got argument: "9"

Why doesn't it work when I try to start application using erl -s

Something like
erl -s crypto start -s application start public_key
works for crypto but not application:start(..). Typically I have call application supervisor but not application itself. What's the normal way of doing it?
The -s flag expects
Module Fun Arg1 Arg2 ..
and executes it as
module:fun([Arg1, Arg2, ..]).
So, it passes the arguments as a list.
When running -s application start public_key it wil call application:start([public_key]), which isn't supported. This works: application:start(public_key)
I did not found a workaround for it without creating a module that contains a function to start up the public_key application, like:
-module(myapp).
-export([start/1]).
start([App]) -> application:start(App).
And call it like
erl -s crypto start -s myapp start public_key

Resources