我可以做的最簡單的事情是基於this github回購。所以,你需要以下條件:
reader.c
#include "erl_driver.h"
#include <stdio.h>
typedef struct {
ErlDrvPort drv_port;
} state;
static ErlDrvData start(ErlDrvPort port, char *command) {
state *st = (state *)driver_alloc(sizeof(state));
st->drv_port = port;
set_port_control_flags(port, PORT_CONTROL_FLAG_BINARY);
driver_select(st->drv_port, (ErlDrvEvent)(size_t)fileno(stdin), DO_READ, 1);
return (ErlDrvData)st;
}
static void stop(ErlDrvData drvstate) {
state *st = (state *)drvstate;
driver_select(st->drv_port, (ErlDrvEvent)(size_t)fileno(stdin), DO_READ, 0);
driver_free(drvstate);
}
static void do_getch(ErlDrvData drvstate, ErlDrvEvent event) {
state *st = (state *)drvstate;
char* buf = malloc(1);
buf[0] = getchar();
driver_output(st->drv_port, buf, 1);
}
ErlDrvEntry driver_entry = {
NULL,
start,
stop,
NULL,
do_getch,
NULL,
"reader",
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
ERL_DRV_EXTENDED_MARKER,
ERL_DRV_EXTENDED_MAJOR_VERSION,
ERL_DRV_EXTENDED_MINOR_VERSION
};
DRIVER_INIT(reader) {
return &driver_entry;
}
與gcc -o reader.so -fpic -shared reader.c
編譯。 然後,你需要在reader.erl
-module(reader).
-behaviour(gen_server).
-export([start/0, init/1, terminate/2, read/0, handle_cast/2, code_change/3, handle_call/3, handle_info/2, getch/0]).
-record(state, {port, caller}).
start() ->
gen_server:start_link({local, ?MODULE}, ?MODULE, no_args, []).
getch() ->
gen_server:call(?MODULE, getch, infinity).
handle_call(getch, From, #state{caller = undefined} = State) ->
{noreply, State#state{caller = From}};
handle_call(getch, _From, State) ->
{reply, -1, State}.
handle_info({_Port, {data, _Binary}}, #state{ caller = undefined } = State) ->
{noreply, State};
handle_info({_Port, {data, Binary}}, State) ->
gen_server:reply(State#state.caller, binary_to_list(Binary)),
{noreply, State#state{ caller = undefined }}.
init(no_args) ->
case erl_ddll:load(".","reader") of
ok ->
Port = erlang:open_port({spawn, "reader"}, [binary]),
{ok, #state{port = Port}};
{error, ErrorCode} ->
exit({driver_error, erl_ddll:format_error(ErrorCode)})
end.
handle_cast(stop, State) ->
{stop, normal, State};
handle_cast(_, State) ->
{noreply, State}.
code_change(_, State, _) ->
{noreply, State}.
terminate(_Reason, State) ->
erlang:port_close(State#state.port),
erl_ddll:unload("reader").
read() ->
C = getch(),
case C of
"q" ->
gen_server:cast(?MODULE, stop);
_ ->
io:fwrite("Input received~n",[]),
read()
end.
與erlc reader.erl
編譯。
然後在IEX :reader.start(); :reader.read()
它會發出警告,stdin
已被劫持,併爲每一個按鍵你輸入收到。唯一的問題是,當您按q服務器終止,但stdin
不可訪問。
該eralng IO系統是非常不同於其他語言和完全自定義。這使它表現出奇怪的方式。我看過很多次這樣的問題,但不幸的是,我從來沒有見過一個好的答案。據我所知,像你問的東西是不可能的,但我可能是錯的,所以我不會發布這個答案。 – michalmuskala
@michalmuskala我的問題的最後一部分實際上包含了可以如何完成的隨時可用的答案。唯一的問題是它看起來過於複雜,我懷疑沒有人已經解決了這個問題。 – mudasobwa