Skip to content

Instantly share code, notes, and snippets.

@sg2342
Created April 23, 2015 19:16
Show Gist options
  • Save sg2342/669c896afbd12626366c to your computer and use it in GitHub Desktop.
Save sg2342/669c896afbd12626366c to your computer and use it in GitHub Desktop.
erlang sendfile FreeBSD testcase
#!/usr/bin/env escript
%% -*- erlang -*-
%%! -smp enable
%%
-module(sendfile_tc).
-export([main/1]).
main([]) ->
FileName = "/tmp/sendfile_tc_64m",
Port = 1234,
ok = file:write_file(FileName,<<0:(1024 * 1024 * 64)>>),
{ok, LS} = gen_tcp:listen(Port,
[binary, inet, {active, false},
{reuseaddr, true}]),
Pid = spawn(fun() ->
receive go -> ok end,
server_loop(FileName, LS, undefined, 0)
end),
ok = gen_tcp:controlling_process(LS, Pid),
Pid ! go,
client("127.0.0.1", Port),
ok = file:delete(FileName).
server_loop(FileName, LS, Sent0, Cnt) ->
{ok, S} = gen_tcp:accept(LS),
case sendfile(FileName, S) of
Sent when Sent0 == undefined; Sent == Sent0 ->
server_loop(FileName, LS, Sent, Cnt + 1);
Sent ->
gen_tcp:close(LS),
io:format("sendfile failed after ~p: ~p =/= ~p ~n",
[Cnt, Sent0, Sent])
end.
sendfile(FileName, S) ->
{ok, Fd} = file:open(FileName,[raw, read, binary]),
{ok, Sent} = file:sendfile(Fd, S, 0, 0, []),
gen_tcp:close(S), Sent.
client(Addr, Port) ->
case gen_tcp:connect(Addr, Port, [binary, inet, {active, false}]) of
{ok, S} ->
client_recv(S),
client(Addr, Port);
{error, _} = E ->
io:format("client failed to connect: ~p ~n", [E])
end.
client_recv(S) ->
case gen_tcp:recv(S, 0) of
{ok, _} -> client_recv(S);
{error, closed} -> ok;
{error, _} -> gen_tcp:close(S)
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment