Search code examples
erlangpidets

Erlang: Store PID in ETS


In a server I am trying to store it's connected clients and their PIDs in an ets-table.

The table is created as the server is initiated

initate_server() ->
                ets:new(users, [set, named_table]).

When a user is connected to the server I'm calling a function

add_user(PID, Nick) ->
         ets:insert_new(users, {Nick, PID}).

This in turn generates an error saying I'm using a bad argument above. Is it possible to store a PID in an ets-table like this?

The error says the following:

 Something went very wrong! 
    {{case_clause,   
      {'EXIT',    
       {badarg,
        [{ets,insert,[users,{"user01", <0.66.0>}],[]},
          {server, loop, 2,
           [{file,

        filenames and such...

Solution

  • Yes, you can store pids in ETS tables. The reason for the badarg error is probably access control.

    By default, ETS tables are created with protected access. That means that any process can read values from the table, but only the process that created the table can write values to it. Depending on how you want it to work, you could either have the client process send a message to the server to insert new values, or create the table with the public option, which lets any process write to the table.