Kamrul Khan
Kamrul Khan

Reputation: 3350

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

Upvotes: 2

Views: 734

Answers (1)

Steve Vinoski
Steve Vinoski

Reputation: 20014

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.

Upvotes: 7

Related Questions