erlang,elixir,otp , Getting a sibling process in Elixir


Getting a sibling process in Elixir

Question:

Tag: erlang,elixir,otp

I have an Elixir/Erlang process tree:

parent (Supervisor)
├── child1 (GenServer)
└── child2 (GenServer)

child1 (a DB client) has information that child2 needs to use. What's a good way to pass a reference from the Supervisor process to child2 so that child2 will always have a valid reference to child1? Do I just need to restructure my app so that child2 is supervised by child1?


Answer:

The simplest way would probably be for child1 and child2 to be registered under local aliases. You can do that while starting your GenServer by passing the name option:

defmodule Child1 do
  use GenServer

  def start_link do
    GenServer.start_link(__MODULE__, [], name: __MODULE__)
  end
end

In this case a process backed by the Child1 module will be registered locally under an alias Child1. Then if you want to send it messages you can use that alias instead of a PID.

defmodule Child1 do
  # ...

  def get_data do
    GenServer.call(__MODULE__, :get_data)
  end

  def handle_call(:get_data, _from, state) do
    {:reply, extract_data_from_state(state), state}
  end
end

If you want a more complex solution where for example many different processes of the same type may be registered, take a look at the gproc library


Related:


erlang os:cmd() command with UTF8 binary


unicode,encoding,erlang,utf
I'm trying to get an Erlang function to execute a bash command containing unicode characters. For example, I want to execute the equivalent of: touch /home/jani/ჟანიweł I put that command in variable D, for example: io:fwrite("~ts", [list_to_binary(D)]). touch /home/jani/ჟანიwełok but after I execute: os:cmd(D) I get file called á??á??á??á??weÅ?. How...

How to list all the bucket types in riak?


erlang,riak
Using Riak Client(erlang), I can list all the buckets of the default bucket type. But how can I list all the bucket types? Or If I can't do this by the client, how can I find out about this?

Erlang pass-by-reference nuances


erlang,pass-by-reference
9> A = lists:seq(1,10). [1,2,3,4,5,6,7,8,9,10] 13> Fn = fun (L) -> [0|L] end. #Fun<erl_eval.6.90072148> 14> Fn(A). [0,1,2,3,4,5,6,7,8,9,10] 15> A. [1,2,3,4,5,6,7,8,9,10] If erlang internally passes by reference (see this), why does the value of A not reflect the change? What fundamental am I missing about passing-by-reference or erlang?...

Why doesn't spawn link cause the calling process to die?


erlang,erlang-shell
From the example given here, Erlang and process_flag(trap_exit, true) -module(play). -compile(export_all). start() -> process_flag(trap_exit, true), spawn_link(?MODULE, inverse, [***0***]), loop(). loop() -> receive Msg -> io:format("~p~n", [Msg]) end, loop(). inverse(N) -> 1/N. If I run it as, A = spawn(play, start, []). The spawned process <0.40.0> dies as it is suppose...

What does BEAM stand for in iex for the Elixir programming language?


architecture,elixir,acronym,beam,lightweight-processes
I'm sort of curious as to what the B. E. A. and M. stand for. I recall seeing an explanation of the acronym BEAM, but I have not managed to find it again. It comes up in error codes: ➜ gentoo iex Erlang/OTP 17 [erts-6.4.1] [source] [64-bit] [smp:8:8] [async-threads:10] [kernel-poll:false]...

Riak mapReduce fails with > 15 records


mapreduce,erlang,riak
Problem I've been learning Riak and ran into an issue with mapReduce. My mapReduce functions work fine when there's 15 records, but after that, it throws a stack trace error. I'm new to Riak and Erlang, so I'm unsure whether it's my code or it's Riak. Any advice on how...

Where can I put my Plugs and then use them from different controllers in my Phoenix app?


elixir,phoenix-framework
I'm creating my first Elixir-Phoenix app. I've written a few plugs that I want to use in multiple controllers, right now there is a lot of code duplication since the Plug code is being repeated in all of my controllers. My question is, is there a file where I can...

Getting a sibling process in Elixir


erlang,elixir,otp
I have an Elixir/Erlang process tree: parent (Supervisor) ├── child1 (GenServer) └── child2 (GenServer) child1 (a DB client) has information that child2 needs to use. What's a good way to pass a reference from the Supervisor process to child2 so that child2 will always have a valid reference to child1?...

How Can We Clear the Screen in Iex on Windows


windows,elixir
Please how can we clear the screen in Iex on Windows Documented method in Iex help does not work: clear/0 — clears the screen This StackOverflow Answer also does not work in Windows....

Horribly redundant Phoenix controller


elixir,phoenix-framework,ecto
I'm doing my first Phoenix application, and trying to do new/2 controller. The code I wrote is def new(conn, %{"fbid" => fbid, "latitude" => lat, "longitude" => lng, "content" => content}) do {fbid, _} = Integer.parse(fbid); {lat, _} = Float.parse(lat); {lng, _} = Float.parse(lng); chats = %Chat{:fbid => fbid, :latitude...

Erlang spawning large amounts of C processes


c,multithreading,lua,erlang,ffi
I've been looking into how I could embed languages (let's use Lua as an example) in Erlang. This of course isn't a new idea and there are many libraries out there that can do this. However I was wondering if it was possible to start a Genserver with state which...

passing arrays to a function in erlang


arrays,function,erlang,arguments
I am new to erlang programming and as a matter of fact no very experienced programmer. I need to pass an array to a function and then manipulate it.. however I have so far not be this what I found. module(easy). export([myfunction/1]). myfunction([myarray]) -> %% mycode.. hier I will need...

Erlang: Returning a function from a function


erlang
I know Erlang supports anonymous functions. My question is, can I return a function from a function then call that returned function from outside? If so, how do I do it? I know this is possible in many languages such as C and Python. Here is what I tried to...

Erlang based chat (load balancing and notifications distribution)


erlang
We are going to develop a backend for our messenger, so I have one idea which I want describe here, maybe someone can give me an advice. 1) Idea: Nginx - redirects request to random node (round robin) -> Erlang cluster - redirects to actual node (we choose node with...

Fetching and updating data in mnesia


erlang,mnesia
I have multiple mnesia tuples like (GroupID is the primary key) {GroupID, GroupName, GroupType, GroupDescription, GroupTag, CreatorID, AdminID, MemberList, Counter}. MemberList = "[email protected],[email protected],[email protected]". GroupName = "Any String Value". % e.g.: "basketball" GroupTag = "comma separated values". % e.g.: "Sports,Cricket,Fifa,Ronaldo" I will pass a character or word to a function. This...

How to delete a Phoenix Session?


elixir,phoenix-framework
I'm going through the Phoenix Guide on Sessions. It explains it very well how I can bind data to a session using put_session and fetch the value later using get_session but it doesn't tell how I can delete a User's session. From the guide: defmodule HelloPhoenix.PageController do use Phoenix.Controller def...

Manipulating XML element to get value from Sub-element in Erlang


xml,erlang,ejabberd
I have this in Packet: {xmlelement,"message", [{"from", "[email protected]/26526129921433241378891365"}, {"to", "[email protected]/30014432481433242528199830"}], [{xmlelement,"received", [{"xmlns", "urn:xmpp:receipts"}, {"id", "018A12FB-0718-4304-87FD-430C59EDB4F9"}], []}]} I just need to get the value of the id attribute under the received XML element....

how to handle low_entropy exception of crypto:strong_rand_bytes(N)?


openssl,erlang
I want to generate cryptographically strong pseudorandom numbers in erlang for session IDs. There is crypto:strong_rand_bytes(N). What if it throws the low_entropy exception? From http://www.erlang.org/doc/man/crypto.html#strong_rand_bytes-1 strong_rand_bytes(N) -> binary() Types: N = integer() Generates N bytes randomly uniform 0..255, and returns the result in a binary. Uses a cryptographically secure prng...

Value from binding in LFE interpreter using Erlang


erlang,lisp,lfe
I'd like to use Lisp Flavored Erlang as a scripting extension language for an Erlang application. If you want, in a similar way GNU Emacs is configured and extended via Emacs Lisp. I know that the argument is wide and structured; but in the specific case of this question I'd...

In Elixir how do you initialize a struct with a map variable


elixir,elixir-framework
I know its possible to create a struct via %User{ email: '[email protected]' }. But if I had a variable params = %{email: '[email protected]'} is there a way to create that struct using that variable for eg, %User{ params }. This gives an error, just wondering if you can explode it...

How to Log something in Controller when Phoenix Server is running?


elixir,phoenix-framework
Well, the question is pretty clear. I'm trying to print some debug information from one of my Controllers in my Phoenix App when the Server is running. defmodule PhoenixApp.TopicController do use PhoenixApp.Web, :controller alias PhoenixApp.Topic plug :action def index(conn, _params) do # ... log "this text" # ... render(conn, "index.html")...

Erlang syntax error unclear


function,variables,if-statement,functional-programming,erlang
I just got started with Erlang. I am trying if statement. I found out one particular behavior which I do not understand. the following statement does work perfectly. some_comp(Arg1) -> if (cal(Arg1)>50000)->'reached'; true -> 'invalid' end. cal(Arg2)-> %% some calculation. However the following shows an error syntax near if: some_comp(Arg1)...

Getting SSL related error against my request to Ejabberd


android,sockets,ssl,erlang,ejabberd
Following is the code snippet where i open a socket to write APNS notifications on: get_socket()-> %%Options Options = [{certfile, ?Cert}, {keyfile, ?Key}, {mode, binary}], %%ssl connection ssl:connect(?Address, ?Port, Options, infinity) . close_socket(Socket)-> ssl:close(Socket). I am getting the following crash in my ejabberd.log file 2015-06-05 12:33:17.112 [error] <0.3134.0> gen_fsm <0.3134.0>...

Does Erlang has Map?


erlang
It seems that Erlang introduced maps in version R17A. But, if I go to downloads I only see version 17.5, there's no version R17A. So, is it released and stable yet? Does the latest stable Erlang has Map support?...

Erlang driver erl_errno issue


erlang,erlang-driver
I am playing with erl_driver. Start callback of my driver is below: ErlDrvData drv_start(ErlDrvPort port, char* command) { char* file_name = command + sizeof(drv_name); GenTtyData* port_data = (GenTtyData*)driver_alloc(sizeof(GenTtyData)); erl_errno = gt_open(file_name, &port_data->file); if (erl_errno != 0) { // Assertion there is just to show you my intention assert(erl_errno == ENOENT);...

First word of binary string erlang


functional-programming,erlang,pattern-matching
I need to do something like this <<"Some text in binary">>, and it should return <<"Some">. How can i do it without split function, only by pattern matching and select/if cases with Erlang. Thank you.

Elixir exrm release crashes on eredis start_link


erlang,elixir,exrm
I'm fairly new to Elixir and this is the first app that I'm attempting to release using exrm. My app interacts with a Redis database for consuming jobs from a queue (using exq), and also stores results of processed jobs in Redis using eredis. My app works perfectly when I...

ctrl+G in erl doesn't work


unicode,encoding,utf-8,erlang,docker
I'm trying to interconnect erlang nodes, but entering ctrl+G doesn not work: Eshell V6.4.1 (abort with ^G) 1> ^G Eshell V6.4.1 (abort with ^G) 1> ^G Eshell V6.4.1 (abort with ^G) 1> ^G Eshell V6.4.1 (abort with ^G) any idea why this can happen? I was thinking about locale settings,...

How to run Elixir application?


elixir
What is the correct way to run an Elixir application? I'm creating a simple project by: mix new app and after that I can do: mix run which basically compiles my app once. So when I add: IO.puts "running" in lib/app.ex I see "running" only for the first time, each...

Rails' before_filter equivalent in Phoenix


ruby-on-rails,elixir,phoenix-framework
I've just started working on my first Phoenix app, and the issue is that I have some common lines of code in every action in my controller, that I would like to separate out. These lines fetch data from multiple Ecto Models and saves them to variables for use. In...

What is the number that shows up after you define an anonymous function in elixir?


elixir
When you define an anonymous function in elixir you get a result like this. #Function<6.90072148/1 in :erl_eval.expr/5> What I've noticed is that the number is based on the arity of the function. So a 1 arg function is always #Function<6.90072148/1 in :erl_eval.expr/5> A two arg function is always #Function<12.90072148/2 in...

Fast mutable objects in Erlang


erlang
What is the best approach to store and manage high-performance mutable objects in Erlang? Assume that I want to write really simple online game server with realtime gameplay. Somehow I need to represent player's state in Erlang memory. For example, it could be just a simple tuple like {name, "Bob",...

What is the difference between .app and .app.src files in Erlang?


erlang
I found these description in the Erlang doc and learnyousomeerlang.com, but not sure which one is the "Application Resource File". When should I use .app and .app.src? 7.3 Application Resource File http://www.erlang.org/doc/design_principles/applications.html The Application Resource File http://learnyousomeerlang.com/building-otp-applications...

How to delete the whole directory which is not empty?


erlang
I want to clean the temporary for collecting resource. The file module only has del_dir/1 which require the directory is empty. But there is not function the get the all files in the directory (with absolute path") The source code is as follows, how to correct it? delete_path(X)-> {ok,List} =...

Sort List elements in Elixir Lang


elixir
I have a list of strings that I want to order in two ways. Alphabetically By string length ...

erlang processes and message passing architecture


concurrency,process,erlang,messages
The task I have in hand is to read the lines of large file, process them, and return ordered results. My algorithm is: start with master process that will evaluate the workload (written in the first line of the file) spawn worker processes: each worker will read part of the...

Type errors in dialyzer in function with specified type


erlang,dialyzer
I am receiving an error in dialyzer when it analyzes the following function. -spec do_request(Method, Type, Url, Expect, Headers, Body, Client) -> Response::client_response() when Method :: method(), Type :: content_type(), Url :: url(), Expect :: status_codes(), Headers :: headers(), Body :: body(), Client :: #client{}. do_request(Method, Type, Url, Expect, Headers,...

“Cannot begin test transaction because we are already inside one”


elixir,phoenix-framework,ecto
I followed this tutorial and my simple test always fail with this error 1) test /index returns a list of contacts (WorldNote.ChatsControllerTest) test/controllers/chats_controller_test.exs:16 ** (RuntimeError) cannot begin test transaction because we are already inside one stacktrace: (ecto) lib/ecto/adapters/sql.ex:321: anonymous fn/6 in Ecto.Adapters.SQL.start_test_transaction/3 (ecto) lib/ecto/adapters/sql.ex:615: Ecto.Adapters.SQL.pool_transaction/4 (ecto) lib/ecto/adapters/sql.ex:314: Ecto.Adapters.SQL.start_test_transaction/3...

Importing test code in elixir unit test


elixir,mix
I'm writing tests of some Elixir code that interacts with SSH. In my tests, I'd like to start an SSH server that I can run my code against. I'd prefer to store this code in it's own file in the test directory, and have it imported by various different tests....

Mnesia pagination with fragmented table


pagination,erlang,mnesia
I have a mnesia table configured as follow: -record(space, {id, t, s, a, l}). mnesia:create_table(space, [ {disc_only_copies, nodes()}, {frag_properties, [ {n_fragments, 400}, {n_disc_copies, 1}]}, {attributes, record_info(fields, space)}]), I have at least 4 million records for test purposes on this table. I have implemented something like this Pagination search in Erlang...

Output tabular data with IO.ANSI


elixir
I would like to render a 2-dimensional list to a nice tabular output, using an ANSI escape sequences to control the formatting. So given this data: data = [ [ 100, 20, 30 ], [ 20, 10, 20 ], [ 50, 400, 20 ] ] I would like to output...

erlang message passing architecture


process,erlang,messaging
In erlang if two processes A and B are sending message to a process C simultaneously. Will there be a race condition? C ! {very large message} sent by A C ! {very large message} sent by B Will C receive the complete message from A and then proceed for...

Optional POST parameters in Elixir Phoenix


elixir,phoenix-framework
I have a phoenix route that I want to POST some form data to, however there are about 4 fields of the form that are optional (the form is constructed by the end user and therefore these fields may not exist in the POST payload) In the Phoenix controller for...

How to invoke Erlang function with variable?


erlang
4> abs(1). 1 5> X = abs. abs 6> X(1). ** exception error: bad function abs 7> erlang:X(1). 1 8> Is there any particular reason why I have to use the module name when I invoke a function with a variable? This isn't going to work for me because, well,...

Why Rem operator in Elixir returns negative numbers?


elixir
I am trying a simple operation rem(-1, 25) I expect that to be the reminder of integer division and return 24 (the same e.g. as in Ruby) but it returns -1. Am I doing something wrong? Is the behavior broken on elixir?...

Does the pattern [_|_] in Erlang mean anything specific?


erlang
I am learning Erlang from Learn You Some Erlang and I've seen the pattern [_|_] twice already but couldn't find any info on it. This usage seems superfluous because omitting it from (1) and subsituting it with _ in (2) yields the same result without degrading readability. It is my...

Phoenix - controller with multiple render


elixir,phoenix-framework
Trying to create an app with Elixir + Phoenix, that would be able to handle both "browser" and "api" requests to handle its resources. Is it possible to do it without having to do something like that : scope "/", App do pipe_through :browser resources "/users", UserController end scope "/api",...

How to stub (or prevent running) of a call to a worker in my ExUnit test?


elixir,phoenix-framework
I have a Phoenix app (which is just a restful api with no front end) and one of the controllers does some stuff which I want to test, but at the end of the controller it calls a dispatcher which sends a payload off to a worker (run under poolboy)...