rdo
rdo

Reputation: 3982

How to continuously show os command output in erlang?

I need continuously show stdout/stderr from os command in erlang. In ruby I can implement it with following code:

s1, s2 , s3, t = Open3.popen3('for %a in (1 2 3 4 5 6 7 8 9) do (echo message & sleep 2 ) 2>&1 ')

s2.each do |l|
    puts l
end

it will show 'message\n message\n' in 'real time' - does not wait end of process.

I've tried os:cmd(..) and

1> P5 = erlang:open_port({spawn, "ruby rtest.rb"}, [stderr_to_stdout, in, exit_s
tatus, binary,stream, {line, 255}]).
#Port<0.505>
2> receive {P5, Data} -> io:format("Data ~p~n",[Data]) end.
Data {data,{eol,<<>>}}
ok

but both of them wait end of process.

Are the any optional for continuously stdout reading in Erlang?

EDIT: In other words I look for a popen (c/c++; proc_open(php) and etc) function in erlang

EDIT2 Code, that works on linux (tested on centos6.2). Thanks for vinod:

-module(test).
-export([run/0]).


run() ->  
    P5 = erlang:open_port({spawn, "sh test.sh"}, 
    [stderr_to_stdout, in, exit_status,stream, {line, 255}]), 
    loop(P5).

loop(P) ->
       receive{P, Data} -> 
           io:format("Data ~p~n",[Data]),
       loop(P)
       end.

Output:

10> c(test).
{ok,test}
11> test:run().
Data {data,{eol,"1"}}
Data {data,{eol,"2"}}
Data {data,{eol,"3"}}
Data {data,{eol,"4"}}
Data {data,{eol,"5"}}
Data {data,{eol,"6"}}
Data {data,{eol,"7"}}
Data {data,{eol,"8"}}
Data {data,{eol,"9"}}
Data {data,{eol,"10"}}
Data {exit_status,0}

Upvotes: 4

Views: 1933

Answers (1)

Vinod
Vinod

Reputation: 2243

If I understand correctly, you want to continue to execute your program in concurrent with the os command. In Erlang you can just spawn a process which does that and you can continue. For example

1> spawn(fun() ->  
       P5 = erlang:open_port({spawn, "ruby rtest.rb"}, 
                             [stderr_to_stdout, in, exit_status, 
                              binary,stream, {line, 255}]), 
       receive {P5, Data} -> 
           io:format("Data ~p~n",[Data]) 
       end  
   end).
<0.32.0>
2> 5+5.
10
3>

Better to write in a module so that you can understand it better.

Upvotes: 6

Related Questions