problems starting two os:cmd's

Ulf Wiger etxuwig@REDACTED
Wed Oct 10 11:34:31 CEST 2001


In OTP R6, os:cmd/1 is serialized using a gen_server.
This was originally done because open_port() relied on fork(),
which could cause huge problems in very large BEAM-processes.

Nowadays (since well before OTP R6), open_port() uses vfork(),
which doesn't automatically map the same amount of memory as the
host process. This means that you can easily and safely write
your own os_cmd/1, e.g. like this:

os_cmd(Cmd) ->
    Command = binary_to_list(
                list_to_binary(["sh -c '", Cmd,
                                "' 2>&1"])),
    Port = open_port({spawn, Command}, [stream, eof]),
    get_data(Port, []).

get_data(Port, Sofar) ->
    receive
        {Port, {data, Bytes}} ->
            get_data(Port, Sofar ++ Bytes);
        {Port, eof} ->
            Port ! {self(), close},
            receive
                {Port, closed} ->
                    true
            end,
            receive
                {'EXIT', Port, _} ->
                    ok
            after 1 ->
                    ok
            end,
            Sofar;
        {'EXIT', Port, _} ->
            Sofar
    after 120000 ->
            exit(timeout)
    end.



On Wed, 10 Oct 2001, Nico Weling wrote:

>Hi all,
>
>I have problems starting an os:cmd in two different processes.
>
>Process 1:
>   ...
>   ScreenOutput = os:cmd("sendfax -l /dev/mobile0" ++
                          "  " ++ BNumber ++ "  " ++
                          Filename"),
>   ...
>
>Process 2:
>   ...
>   ScreenOutput = os:cmd("mgetty -s 115200 /dev/mobile1"),
>   ...
>
>If the 1st os:cmd is running the 2nd os:cmd("mg....") will
>start it's execution if the 1st os:cmd is finished. (both
>os:cmd's are running in different erlang processes on the same
>node)
>
>If I start the os:cmd's in the background:
>
>	os:cmd("sendfax -l /dev/mobile0" ++ "  " ++
               BNumber ++ "  " ++ Filename" ++ "&"),
>	os:cmd("mgetty -s 115200 /dev/mobile1 &"),
>
>it works fine.
>If I start the os:cmd's in two different Erlang-shells is also
>works fine.
>
>
>Can somebody tell me what happens here and how I can solve this
>problem. I am using Erlang R6. (I need to stick to this
>release)
>
>
>Thanks a lot,
>
>best regards Nico.
>

-- 
Ulf Wiger                                    tfn: +46  8 719 81 95
Senior System Architect                      mob: +46 70 519 81 95
Strategic Product & System Management    ATM Multiservice Networks
Data Backbone & Optical Services Division      Ericsson Telecom AB




More information about the erlang-questions mailing list