Two ways to execute the Linux command by "Erlang"

Source: Internet
Author: User

os.cmd (cmd)

The OS module provides the CMD function to execute Linux system shell commands (you can also execute Windows commands). Returns the standard output string result of a cmd command. For example, execute Os:cmd ("date") on a Linux system. Time to return to Linux. This is relatively simple and, in general, satisfies most of the requirements.

Erlang:open_port (PortName, portsettings)

When Os.cmd (CMD) does not meet your needs, you can use the powerful Open_port (PortName, portsettings) to solve. The simplest requirement, I want to execute a Linux command, but also need to return the exit code. Os.cmd (CMD) is a bit nasty. Also do not think that with Open_port (PortName, portsettings) can completely replace the os.com (CMD). It takes a price to be strong.

Percent benefit: You can return to exit status and the execution process
Percent disadvantage: very affect performance, open_port execution, BEAM.SMP will block

It is not recommended to use Erlang:open_port (PortName, Portsettings) when the performance requirements of the system are relatively high.

Here is a very useful code that returns the exit status and execution results.

My_exec (Command)Port=Open_port ({spawn, Command}, [Stream, in, EOF, hide, Exit_status]), Result=Get_data (port, []), Result.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 After1,%Force Context Switch OKEnd, ExitCode=Receive{Port, {exit_status, Code}}-CodeEnd, {ExitCode, Lists:flatten (SOFAR)}End.

Reference Documentation:

Http://erlang.org/doc/man/os.html#cmd-1

Http://erlang.org/doc/man/erlang.html#open_port-2

Two ways to execute the Linux command by "Erlang"

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.