文章摘要
This article describes a program written in an unspecified language that processes data through a port. The program, named `my_exec`, executes a command in parallel and reads data from the specified port, handling it using a recursive function called `get_data`. The `get_data` function reads data from the port in a loop, appending it to a list, until it encounters an end-of-file (`eof`) or receives an exit command. When `eof` is detected, the port is closed, and the program terminates successfully. If the exit command is received, the program stops and returns a success result. The program also handles context switching to improve performance. The core functionality revolves around parallel execution, data processing, and exit handling.
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.
© 版权声明
文章版权归作者所有,未经允许请勿转载。