os.cmd(Cmd)
os模块提供了cmd函数可以执行linux系统shell命令(也可以执行windows命令)。返回一个Cmd命令的标准输出字符串结果。例如在linux系统中执行os:cmd("date"). 返回linux的时间。 这种比较简单,一般情况下,也满足了大部分需求。
erlang:open_port(PortName, PortSettings)
当os.cmd(Cmd) 满足不了你的需求的时候,就可以用强大的open_port(PortName, PortSettings) 来解决了。最简单的需求,我要执行一个linux命令,而且还需要返回退出码。os.cmd(Cmd) 就有些捉急了。也不要以为有了open_port(PortName, PortSettings) 就可以完全替代os.com(Cmd) 了。强大是需要代价的。
%% 优点:可以返回exit status 和执行过程
%% 缺点: 非常影响性能, open_port执行的时候,beam.smp会阻塞
当对本身系统的性能要求比较高的时候,不建议使用erlang:open_port(PortName, PortSettings) .
下面是一段很好用的代码,返回exit status 和执行结果。
复制代码 代码如下:
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
after 1 -> % force context switch
ok
end,
ExitCode =
receive
{Port, {exit_status, Code}} ->
Code
end,
{ExitCode, lists:flatten(Sofar)}
end.
Erlang,执行linux命令
更新动态
- 群星《发烧混声金唱盘》3CD[MP3][481M]
- DominikWagner-DoubleBassRhapsody(2023)[24-48]FLAC
- 和平之月系列PMR-0048贾鹏芳《浪漫Roman》[WAV+CUE]
- 和平之月系列PMR-0063贾鹏芳二胡《月光Moonlight》[WAV+CUE]
- 黄乙玲.1992-悲恋梦【歌林】【WAV+CUE】
- 许巍.2001-我只有两天精丫红星生产社】【WAV+CUE】
- 王芷蕾.2001-盛开精选2辑【华纳】【WAV+CUE】
- 群星.2003-LOVE情歌集【正东】【WAV+CUE】
- 张其萍《美丽中国梦》[WAV+CUE]
- 群星《嗨麦顶级中文舞曲·金牌舞曲精逊2CD[WAV分轨]
- 群星《发烧女生 DSD》[WAV+CUE][625M]
- 张学友《私人珍藏(黑胶CD)》2CD[WAV+CUE][1.2G]
- 刘紫玲《紫音幽韵(DSD)》[WAV+CUE][441M]
- 刘珺儿.2004-靓人靓歌5CD【音乐谷】【WAV+CUE】
- 康乔.1991-精丫丽风】【WAV+CUE】