[erlang-questions] Proper way to run C code without crashing the VM
Vincent de Phily
vincent.dephily@REDACTED
Fri Aug 18 18:08:58 CEST 2017
On 2017-08-16 15:53, code wiget wrote:
> Hello,
>
> I have been reading about NIF’s
> here: http://erlang.org/doc/tutorial/nif.html but it seems like they are
> incredibly unsafe: “it is also the least safe, because a crash in a NIF
> brings the emulator down too”. The problem here is huge, ideally I can’t
> ever have my Erlang VM close.
Whatever you do, your node *will* close someday, if only due to hardware
failure. If you have high uptime requirements, you should tackle node
redundancy/failover first before worrying about individual node stability.
> What solution do you Erlangers use when you have to run low level code?
The general advice with NIFs is to keep them small/simple/auditable
enough that you can consider them bug-free. Most NIFs are just wrappers
around existing libs, so they're going to be as stable as the underlying
lib.
If the underlying lib is unstable, interface with it using an Erlang
port or via the network.
If you're writing a complex lib yourself (so using NIFs for
performance's sake rather than code reuse), maybe write it in Rust
rather than C/C++ ? I'm looking for an excuse to do that myself. See
https://www.youtube.com/watch?v=lSLTwWqTbKQ
http://hansihe.com/2017/02/05/rustler-safe-erlang-elixir-nifs-in-rust.html
https://github.com/hansihe/Rustler
> My goal is to send a sort of “GET” request with a UUID and I will
> receive back that UUID along with some binary values. My C code works
> with this, but I can’t jeopardize the entire server crashing.
Sounds like you're querying an external server, not doing a lot of
computation locally ? If that's the case, going low-level with NIFs,
ports, etc is probably overkill, you're better off implementing it in
pure Erlang.
Actually, even if you do heavy computation locally, try implementing it
in pure Erlang first : chances are that performance will be good enough,
and you'll have an easyer time debugging and tuning Erlang than C.
--
Vincent de Phily
More information about the erlang-questions
mailing list